C#文件 - 从桌面读取文件并将其写入特定文件

时间:2013-06-22 11:30:41

标签: c# file-io

我创建了一个间隔为5000毫秒的System.Timers.Timer对象。在此计时器的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);
        }
    }

也许我必须在ReadAllLinesFile.AppendText之间设置一点延迟?

1 个答案:

答案 0 :(得分: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方法可确保正确释放所有资源。