我创建了System.Timers.Timer
一个间隔为 5000 毫秒的对象。在Elapsed
此计时器事件中,我正在搜索桌面上出现的新 PDF 文件。如果有新的 PDF 文件,我会将它们添加到特定文件中,但我的程序会捕获此错误:该进程无法访问文件 'C:\Users\Admin\Desktop\StartupFiles.dat' 因为它正在被另一个进程使用. 这是我的代码:
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
也许我必须在and之间设置一点延迟File.AppendText
?