0

我在将文件上传到 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;
    }

有什么办法解决吗?谢谢你

4

0 回答 0