文件系统观察者:System.IO.IOException ("File used by another process")

FileSystemWatcher: System.IO.IOException ("File used by another process")

目前我正在开发一个应用程序,它应该监视特定目录的更改(比如创建了一个新文件),然后将文件上传到 Sharepoint。因此,我使用的是 FileSystemWatcher class,它会抛出一个带有创建文件路径的事件,而我又使用另一种方法来上传文件。问题是:在 Visual Studio 的调试模式下,我意识到我在监视目录中创建的第一个文件被完美上传,即使我一次将多个文件拖到目录中,所有文件都被上传,但是当我这样做时一个接一个文件我得到一个异常,第二个文件已经在使用中。所以我将 File1.txt 拖到目录中,它可以工作,但是,当我在尝试创建要上传到 Sharepoint 的文件流时得到 System.IO.IOException 后立即将 file2.txt 拖到目录中我说 file2.txt 正在被另一个进程使用。

FileSystemWatcher 的代码:

 public void StartWatcher()
        {
            FileSystemWatcher fsw = new FileSystemWatcher(this.path);

            fsw.IncludeSubdirectories = true;

            fsw.EnableRaisingEvents = true;



            fsw.Created += new FileSystemEventHandler(CreateFile);


            try
            {

                while (true)
                {
                    fsw.WaitForChanged(WatcherChangeTypes.All);
                }
            }
            catch
            { }

                fsw.EnableRaisingEvents = false;

        }

调用的CreateFile()方法
fsw.Created += new FileSystemEventHandler(CreateFile);

看起来像这样:

 private void CreateFile(object sender, FileSystemEventArgs e)
        {
            path = String.Format(e.FullPath);
            filename = Path.GetFileName(path);
            Stream fs = File.OpenRead(@path);
            SPAPI spobj = new SPAPI();
            spobj.SPUploader(fs, filename);
            fs.Close();
        }

异常抛出在

Stream fs = File.OpenRead(@path);

但仅当将第二个文件拖到第一个文件之后的目录中时。奇怪的是,不是第一个文件正在使用,而是我想作为流打开的第二个文件。所以它不是仍然打开并导致异常的流。似乎 FileSystemWatcher 正在使用第二个文件。但是为什么第一个文件可以正常工作,但是当第二个文件拖入目录时就抛出异常?

您可以这样修改使用。希望对您有所帮助

private void CreateFile(object sender, FileSystemEventArgs e)
{
    int until = 5;
    int i = 0;
    bool success = false;
    while (!success && i < until)
    {
        try
        {
            path = String.Format(e.FullPath);
            filename = Path.GetFileName(path);
            using (Stream fs = File.OpenRead(@path);)
            {
                SPAPI spobj = new SPAPI();
                spobj.SPUploader(fs, filename);
            }
            success = true;
        }
        catch
        {
            i++;
            Thread.Sleep(TimeSpan.FromSeconds(1));
        }
    }
}