开发者

Problem Uploading a file via FTP using FtpWebRequest when the file does not already exist on FTP server

开发者 https://www.devze.com 2023-03-30 17:25 出处:网络
This seems like a trivial problem, but my web searches for an answer (even on this site) have forced me to ask the question explicitly.

This seems like a trivial problem, but my web searches for an answer (even on this site) have forced me to ask the question explicitly.

I am uploading a file via FTP from my server to a remote server. My code looks like this...

public void Upload(string fileToUpload)
    {
        // Get the object used to communicate with the server.
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.remoteserver.com/Data/" + fileToUpload);
        request.UsePassive = false;
        request.UseBinary = true;
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.Credentials = new NetworkCredential ("username","password");

        // Copy the contents of the file to the request stream.
        StreamReader sourceStream = new StreamReader(fileToUpload);
        byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEn开发者_如何学Cd());
        sourceStream.Close();
        request.ContentLength = fileContents.Length;

        Stream requestStream = request.GetRequestStream();
        requestStream.Write(fileContents, 0, fileContents.Length);
        requestStream.Close();

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

        response.Close();
    }

This all seems very straight-forward. The problem I am having is that I get a 550 error when the file does not already exist on the remote server. I would assume that if the file doe snot exist, then the file would be created. Further, I assume that if it does that it will be overwritten.

Since this is not the case (at least with writing a new file), I would further assume that I should (a) somehow check for the file first, and (b) create it if it does not exist. But how to do this?

Thanks,

Mike


(comment converted to answer)

What are you passing into fileToUpload, an absolute file path such as c:\File.txt or just a filename like File.txt? Also, do you understand that your program only works with text files, right?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号