使用 File.Create() 后被另一个进程使用的文件 [英] File being used by another process after using File.Create()

查看:20
本文介绍了使用 File.Create() 后被另一个进程使用的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在运行时检测文件是否存在,如果不存在,则创建它.但是,当我尝试写入时出现此错误:

I'm trying to detect if a file exists at runtime, if not, create it. However I'm getting this error when I try to write to it:

进程无法访问文件myfile.ext",因为它正被另一个进程使用.

The process cannot access the file 'myfile.ext' because it is being used by another process.

string filePath = string.Format(@"{0}M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
if (!File.Exists(filePath)) 
{ 
    File.Create(filePath); 
} 

using (StreamWriter sw = File.AppendText(filePath)) 
{ 
    //write my text 
}

关于如何修复它的任何想法?

Any ideas on how to fix it?

推荐答案

File.Create 方法创建文件并在文件上打开一个 FileStream.所以你的文件已经打开了.您根本不需要 file.Create 方法:

The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:

string filePath = @"c:somefilename.txt";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
    //write to the file
}

StreamWriter 构造函数中的布尔值将导致在文件存在时追加内容.

The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.

这篇关于使用 File.Create() 后被另一个进程使用的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆