C#WebClient.UploadFileAsync无法访问该文件,因为它正被另一个进程使用

时间:2014-06-05 10:15:04

标签: c# file-upload process webclient

我正在构建一个简单的应用程序,用于将计算机上的文件夹与远程服务器同步。我使用FileSystelWatcher来检测更改,使用WebClient来上传文件。 问题是,当我尝试上传时,我得到一个异常,说该文件已被使用。我检查了所有进程,但我找不到阻塞的进程。我也试过这个File access error with FileSystemWatcher when multiple files are added to a directory,但问题仍然存在。 以下是我声明FileSysemWatcher的方法:

private void InitFileWatcher()
    {
        try
        {
            watcher = new FileSystemWatcher();
            watcher.Path = FileManager.getSyncDirPath();
            watcher.EnableRaisingEvents = true;
            watcher.IncludeSubdirectories = true;
            watcher.Created += FileManager.FileCreated;
        }
        catch(Exception)
        {
            Console.WriteLine("Error");
        }
    }

FileManager.FileCreated方法:

public static void FileCreated(object sender, FileSystemEventArgs e) 
    {
        Console.WriteLine("File created: " + e.FullPath);
        while (true)
        {
            try
            {
                using (Stream stream = System.IO.File.Open(e.FullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                    if (stream != null)
                    {
                        FileUploader uploader = new FileUploader();
                        uploader.Upload(e.FullPath, new Uri("http://192.168.65.1/test/upload.php"));
                        break;
                    }
                }
            }
            catch (FileNotFoundException ex)
            {
                System.Diagnostics.Trace.WriteLine(string.Format("Output file {0} not yet ready ({1})", e.FullPath, ex.Message));
            }
            catch (IOException ex)
            {
                System.Diagnostics.Trace.WriteLine(string.Format("Output file {0} not yet ready ({1})", e.FullPath, ex.Message));
            }
            catch (UnauthorizedAccessException ex)
            {
                System.Diagnostics.Trace.WriteLine(string.Format("Output file {0} not yet ready ({1})", e.FullPath, ex.Message));
            }
            Thread.Sleep(500);
        }
    }

最后是上传方法:

public void Upload(string file, Uri destination)
    {
        WebClient client = new WebClient();
        client.Headers.Add("Content-Type", "binary/octet-stream");
        client.UploadFileAsync(destination, "POST", file);
    }

感谢您的帮助! :)

2 个答案:

答案 0 :(得分:1)

它不允许您上传文件,因为该文件已使用System.IO.File.Open

打开

如果您要打开文件只是为了检查它的存在,那么您可以使用

File.Exists(path);

答案 1 :(得分:0)

你必须尝试下面提到的代码。

    public void Upload(string file, Uri destination)
    {
       using (WebClient client=new Webclient())
        {
           client.Headers.Add("Content-Type", "binary/octet-stream");
           client.UploadFileAsync(destination, "POST", file);
        }
    }