我正在尝试检测运行时是否存在文件,如果没有,则创建它.但是当我尝试写入时,我收到此错误:
该进程无法访问文件'myfile.ext',因为它正由另一个进程使用.
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
}
Run Code Online (Sandbox Code Playgroud)
关于如何修复它的任何想法?
Car*_*tes 133
File.Create(FilePath).Close();
File.WriteAllText(FileText);
Run Code Online (Sandbox Code Playgroud)
我想更新这个答案,说这不是写入所有文本的最有效方法.如果您需要快速和脏的东西,您应该只使用此代码.
当我回答这个问题时,我还是一个年轻的程序员,那时我觉得我有点天才想出这个答案.
Chr*_*way 108
该File.Create方法创建文件并在文件上打开FileStream.所以你的文件已经打开了.你根本不需要file.Create方法:
string filePath = @"c:\somefilename.txt";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
//write to the file
}
Run Code Online (Sandbox Code Playgroud)
StreamWriter如果文件存在,构造函数中的布尔值将导致附加内容.
Ral*_*ine 25
创建文本文件时,您可以使用以下代码:
System.IO.File.WriteAllText("c:\test.txt", "all of your content here");
Run Code Online (Sandbox Code Playgroud)
使用评论中的代码.必须关闭您创建的文件(流).File.Create将文件流返回到刚刚创建的文件:
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
}
Run Code Online (Sandbox Code Playgroud)
小智 16
FileStream fs= File.Create(ConfigurationManager.AppSettings["file"]);
fs.Close();
Run Code Online (Sandbox Code Playgroud)
小智 9
File.Create返回FileStream.您需要在写入文件时关闭它:
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);
}
Run Code Online (Sandbox Code Playgroud)
您可以使用use来自动关闭文件.
我使用代码段更新了您的问题.在适当缩进之后,立即清楚问题是什么:您使用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
}
Run Code Online (Sandbox Code Playgroud)
哪个使用这个StreamWriter构造函数.
| 归档时间: |
|
| 查看次数: |
166399 次 |
| 最近记录: |