错误550 FTP由两个线程同时上载同一文件

时间:2013-07-03 20:06:09

标签: c# multithreading upload ftp

我在将文件上传到ftp服务器时遇到问题。 该函数工作正常,但如果尝试在多线程中使用它,并且当两个线程同时尝试写同一个文件时,我在第二个线程中得到错误550.

基本上第一个线程创建文件,而第二个线程引发错误。

这是我的代码

 internal bool UploadFtp(IResult result, string directoryPath, string filename, Stream fileContents, bool considerError550=true)
    {
        Thread.Sleep(3000);
        directoryPath = directoryPath.TrimStart('\\');
        string completePath = MachineConnectionParam.Url;

        fileContents.Seek(0, SeekOrigin.Begin);
        if (directoryPath != string.Empty && directoryPath != "\\")
            completePath = completePath + directoryPath;
        FtpWebResponse response = null;
        try
        {
            completePath = completePath.TrimEnd('/');
            filename = filename.TrimStart('/');
            completePath = completePath + "/" + filename;
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(completePath);
            if (request == null)
            {
                result.SetError(Translate.InvalidUrl, completePath);
                return false;
            }
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.UseBinary = true;
            request.UsePassive = false;
            request.KeepAlive = false;
            //request.Timeout = 5000;

            request.Proxy = null;
            request.Credentials = new NetworkCredential(MachineConnectionParam.Username, MachineConnectionParam.Password);

            request.ContentLength = fileContents.Length;

            Stream requestStream = request.GetRequestStream();
            fileContents.CopyTo(requestStream);
            requestStream.Close();

            response = (FtpWebResponse)request.GetResponse();

        }
        catch (Exception e)
        {

            result.SetError(e.Message);
            return false;
        }
        finally
        {
            if (response != null)
                response.Close();
        }
        return true;
    }

任何解决它的想法? 谢谢

0 个答案:

没有答案