我創建了一個間隔爲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()'這裏 –