我正在尝试创建一个创建文本文件的服务,作为教程项目。
但是当我调试它时,我得到The process cannot access the file C:\myfilepath.OnStart.txt because it is being used by another process.
我希望它能够以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");
}
答案 0 :(得分:3)
创建文件时,您错误地将其保持打开状态,这就是您下次无法访问该文件并收到错误的原因。您必须在创建它之后致电.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