2013-06-22 110 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

相关问题