C# 使用File.Create()后另一进程正在使用的文件
我试图在运行时检测文件是否存在,如果不存在,则创建它。但是,当我尝试写入时,会出现以下错误: 进程无法访问文件“myfile.ext”,因为其他进程正在使用该文件C# 使用File.Create()后另一进程正在使用的文件,c#,file-io,C#,File Io,我试图在运行时检测文件是否存在,如果不存在,则创建它。但是,当我尝试写入时,会出现以下错误: 进程无法访问文件“myfile.ext”,因为其他进程正在使用该文件 有关如何修复它的任何想法?创建文本文件时,可以使用以下代码: System.IO.File.WriteAllText("c:\test.txt", "all of your content here"); 使用注释中的代码。您创建的文件(流)必须关闭。File.Create将filestream返回到刚创建的文件: string f
有关如何修复它的任何想法?创建文本文件时,可以使用以下代码:
System.IO.File.WriteAllText("c:\test.txt", "all of your content here");
使用注释中的代码。您创建的文件(流)必须关闭。File.Create将filestream返回到刚创建的文件:
string filePath = "filepath here";
if (!System.IO.File.Exists(filePath))
{
System.IO.FileStream f = System.IO.File.Create(filePath);
f.Close();
}
using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath))
{
//write my text
}
File.Create
方法创建文件并在文件上打开一个FileStream
。所以你的文件已经打开了。您根本不需要文件。创建方法:
string filePath = @"c:\somefilename.txt";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
//write to the file
}
如果文件存在,
StreamWriter
构造函数中的布尔值将导致追加内容。file.Create返回文件流。写入文件后,您需要关闭该文件:
using (FileStream fs = File.Create(path, 1024))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
您可以使用自动关闭文件。我用代码片段更新了您的问题。正确缩进后,问题马上就清楚了:使用
File.Create()
,但不要关闭它返回的FileStream
这样做是不必要的,StreamWriter
已经允许附加到现有文件,并在不存在的情况下创建新文件。像这样:
string filePath = string.Format(@"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre);
using (StreamWriter sw = new StreamWriter(filePath, true)) {
//write my text
}
它使用
我想更新这个答案,说这并不是写所有文本最有效的方式只有当您需要快速且肮脏的东西时,才应使用此代码。
当我回答这个问题时,我还是一个年轻的程序员,当时我认为我是一个天才,能够想出这个答案。这个问题已经得到了回答,但这里有一个真实的解决方案 检查目录是否存在,如果文本文件 存在。我使用它在我编写的Windows服务上创建每日日志文件。我 希望这对别人有帮助
// How to create a log file with a sortable date and add numbering to it if it already exists.
public void CreateLogFile()
{
// filePath usually comes from the App.config file. I've written the value explicitly here for demo purposes.
var filePath = "C:\\Logs";
// Append a backslash if one is not present at the end of the file path.
if (!filePath.EndsWith("\\"))
{
filePath += "\\";
}
// Create the path if it doesn't exist.
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
// Create the file name with a calendar sortable date on the end.
var now = DateTime.Now;
filePath += string.Format("Daily Log [{0}-{1}-{2}].txt", now.Year, now.Month, now.Day);
// Check if the file that is about to be created already exists. If so, append a number to the end.
if (File.Exists(filePath))
{
var counter = 1;
filePath = filePath.Replace(".txt", " (" + counter + ").txt");
while (File.Exists(filePath))
{
filePath = filePath.Replace("(" + counter + ").txt", "(" + (counter + 1) + ").txt");
counter++;
}
}
// Note that after the file is created, the file stream is still open. It needs to be closed
// once it is created if other methods need to access it.
using (var file = File.Create(filePath))
{
file.Close();
}
}
试试这个:它在任何情况下都能工作,如果文件不存在,它会创建它,然后写入它。如果已经存在,则不会有问题,它将打开并写入:
using (FileStream fs= new FileStream(@"File.txt",FileMode.Create,FileAccess.ReadWrite))
{
fs.close();
}
using (StreamWriter sw = new StreamWriter(@"File.txt"))
{
sw.WriteLine("bla bla bla");
sw.Close();
}
我知道这是一个老问题,但我只想抛开这个问题,你仍然可以使用
File.Create(“filename”)”
,只需添加.Dispose()
File.Create(“filename”).Dispose();
这样,它会创建并关闭文件,供下一个进程使用。我想我知道出现此异常的原因。您可能正在多个线程中运行此代码段。我似乎没有关闭选项。下面是代码:string filePath=string.Format(@{0}\M{1}.dat),ConfigurationManager.AppSettings[“DirectoryPath”],成本中心);如果(!File.Exists(filePath)){File.Create(filePath);}使用(StreamWriter sw=File.AppendText(filePath)){//write my text}
File.Create
返回FileStream
,并且它有Close()。人们没有意识到每个问题都有一个更简单的答案。这段代码的缺点是不必要地打开文件两次。此外,根本不需要检查文件是否存在,因为如果文件不存在,FileStream构造函数将自动为您创建它,除非您明确告诉它不要这样做。@reirab这完全是相对的。我需要检查文件是否存在,如果存在,请将其删除并重新创建,因此在我的情况下,最好使用此答案。@S.O.那么您遇到的问题与OP不同,只是一个相关的问题。此外,在您的情况下,您仍然可以使用FileStream(string,FileMode)
构造函数并传递它,这将覆盖任何现有文件。仍然不需要打开文件两次。另外,这个答案是在我发布我的原始评论后编辑的。这个答案的目的是显示你可以在结尾添加.Close()
,所以它在任何情况下都有效。我不信任使用FileStream
的系统,因为我不希望在FileMode上发生异常。创建文件已经存在的,尤其是当我想清除内容而不是通过FileMode追加到内容时。打开。对我来说,FileStream
只有在清除了有问题的文件后才真正起作用,然后才写入文件。由于File.Create
使其处于打开和锁定状态,因此向其添加.Close()
似乎是处理我的场景和S.O.的唯一真正方法。欢迎使用Stackoverflow。您至少应该写简短的描述来描述您的答案/解决方案。使用将通过调用Dispose关闭文件。在您的示例中,虽然OP试图打开一个文件,但已关闭了两次,这一点可以从他的使用中推断出来。我尝试了上述代码,但在创建文件时,以及当文件试图写入文件时,出现了相同的错误,这表明文件正被其他进程使用。@AnmolHod确保您没有使用file.Create()
方法!上面的代码段已经创建了该文件<代码>文件.Create(FilePath).Close()代码>从上面的答案中有这个.Dispose(true);GC.SuppressFinalize((对象)this)代码>在其实现中。对我来说,问题在于我以异步方式(在另一个线程中)编写日志文件:Task.Run()而不等待(故意),这会导致多线程访问同一文件。
// How to create a log file with a sortable date and add numbering to it if it already exists.
public void CreateLogFile()
{
// filePath usually comes from the App.config file. I've written the value explicitly here for demo purposes.
var filePath = "C:\\Logs";
// Append a backslash if one is not present at the end of the file path.
if (!filePath.EndsWith("\\"))
{
filePath += "\\";
}
// Create the path if it doesn't exist.
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
// Create the file name with a calendar sortable date on the end.
var now = DateTime.Now;
filePath += string.Format("Daily Log [{0}-{1}-{2}].txt", now.Year, now.Month, now.Day);
// Check if the file that is about to be created already exists. If so, append a number to the end.
if (File.Exists(filePath))
{
var counter = 1;
filePath = filePath.Replace(".txt", " (" + counter + ").txt");
while (File.Exists(filePath))
{
filePath = filePath.Replace("(" + counter + ").txt", "(" + (counter + 1) + ").txt");
counter++;
}
}
// Note that after the file is created, the file stream is still open. It needs to be closed
// once it is created if other methods need to access it.
using (var file = File.Create(filePath))
{
file.Close();
}
}
using (FileStream fs= new FileStream(@"File.txt",FileMode.Create,FileAccess.ReadWrite))
{
fs.close();
}
using (StreamWriter sw = new StreamWriter(@"File.txt"))
{
sw.WriteLine("bla bla bla");
sw.Close();
}
FileStream fs= File.Create(ConfigurationManager.AppSettings["file"]);
fs.Close();