我正在尝试创建一个创建文本文件的服务,作为教程项目。
但是,当我调试它时,我得到进程无法访问文件 C:\myfilepath.OnStart.txt,因为它正在被另一个进程使用。
我希望它继续以 OnStart(n).txt
等格式创建文件
public void OnDebug()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
Timer t = new Timer(WriteTxt, null, 0, 5000);
}
public static void WriteTxt(Object i)
{
System.IO.File.Create(AppDomain.CurrentDomain.BaseDirectory + "OnStart.txt");
}
最佳答案
创建文件时,您错误地将其保持打开状态,这就是您下次无法访问它并收到错误的原因。创建文件后必须调用 .Dispose()
以释放对文件的引用,如下所示:
File.Create(AppDomain.CurrentDomain.BaseDirectory + "OnStart.txt").Dispose();
如果您想继续创建文件,那么它们每次都需要不同的名称。您可以保留一个全局变量来跟踪这一点,或者可能将一个值传递到 Write 方法中。
全局变量方法
// Keeps track of the last file number with this global variable
private int fileCount;
public void OnDebug()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
fileCount = 0; // Or whatever you want to start with
Timer t = new Timer(WriteTxt, null, 0, 5000);
}
public static void WriteTxt(Object i)
{
// Creates the file name eg: OnStart1.txt
var fileName = string.Format("OnStart{0}.txt", fileCount);
// Use Path.Combine to make paths
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
// Create the file
File.Create(filePath).Dispose();
// Adds 1 to the value
fileCount++;
}
结果:
OnStart0.txt
OnStart1.txt
OnStart2.txt
...
...
OnStart4999.txt
关于c# - 创建txt文件无法访问其他进程正在使用的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35157990/