1

我创建了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

4

1 回答 1

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 方法可确保正确释放所有资源。

于 2013-06-22T12:09:35.347 回答