我创建了一个间隔为5000毫秒的System.Timers.Timer
对象。在此计时器的Elapsed
事件中,我正在搜索桌面上出现的新PDF文件。如果有新的PDF文件,我将它们添加到特定的文件中,但是我的程序会捕获此错误:该进程无法访问文件'C:\ Users \ Admin \ Desktop \ StartupFiles.dat',因为它正在被另一个过程。 这里是我的代码:C#文件 - 从桌面读取文件并将它们写入特定文件
private readonly string fileName = Application.StartupPath + @"\StartupFiles.dat";
private readonly string sourceDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
void timerCheck_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
if (!File.Exists(fileName))
File.Create(fileName);
string[] PDFiles = Directory.GetFiles(sourceDirectory, "*.pdf", SearchOption.TopDirectoryOnly);
string[] textFile = File.ReadAllLines(fileName);
bool exist;
string addText = string.Empty;
foreach (string s in PDFiles) // Check the files from the desktop with the files from the fileName variabile folder
{
exist = false;
foreach (string c in textFile)
{
if (string.Compare(s, c) == 0)
{
exist = true;
break;
}
}
if (!exist)
{
addText += s + '\n';
}
}
if (!string.IsNullOrEmpty(addText)) // If a new PDF appeard on the desktop, save it to file
{
using (StreamWriter sw = File.AppendText(fileName))
{
sw.Write(addText);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
也许我必须设置ReadAllLines
和File.AppendText
之间有点延迟?
访问该文件的其他进程是什么?此代码是否尝试访问定时器已过时事件上的文件,而其前一个已过期事件是否仍在访问该文件? – David
我不知道哪一个是其他进程,这是我正在访问此文件的唯一地方... – charqus
http://stackoverflow.com/a/3189617/1226915所以尝试使用'FileStream'而不是'File.ReadAllLines()'这里 –