2013-06-22 57 views
1

我創建了一個間隔爲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); 
     } 
    } 

也許我必須設置ReadAllLinesFile.AppendText之間有點延遲?

+0

訪問該文件的其他進程是什麼?此代碼是否嘗試訪問定時器已過時事件上的文件,而其前一個已過期事件是否仍在訪問該文件? – David

+0

我不知道哪一個是其他進程,這是我正在訪問此文件的唯一地方... – charqus

+0

http://stackoverflow.com/a/3189617/1226915所以嘗試使用'FileStream'而不是'File.ReadAllLines()'這裏 –

回答

0

@charqus,這應該工作

if (!File.Exists(fileName)) 
    File.Create(fileName).Dispose(); 

string[] PDFiles = Directory.GetFiles(sourceDirectory, "*.pdf", SearchOption.TopDirectoryOnly); 
List<String> fileList = new List<String>(); 
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) 
{ 
    using (BinaryReader r = new BinaryReader(fs)) 
    { 
     fileList.Add(r.ReadString()); 
    } 
} 

string[] textFile = fileList.ToArray(); 

調用Dispose方法確保所有資源都被正確釋放。

+0

他只讀了半行,根本不讀...... – charqus

相關問題