Upload PDF files through FTP in C Sharp

2019-08-19 07:16发布

问题:

I have the following code to upload a pdf file through ftp :

try
        {
            if (!File.Exists(localPath))
                throw new FileNotFoundException(localPath);

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(ftpPath));
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Proxy = null;
            request.UseBinary = true;
            request.Credentials = new NetworkCredential(username, password);

            byte[] data = File.ReadAllBytes(localPath);

            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            if (response == null || (response.StatusCode != FtpStatusCode.CommandOK))
                throw new Exception("Upload failed.");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            throw e;
        }

My problem that it uploads only text without images . How could i upload a file without reading it? I mean i just want to select and rename the file and upload it.

回答1:

Use the WebClient class and use then the UploadFile Method. From msdn

 String uriString = Console.ReadLine();

// Create a new WebClient instance.
WebClient myWebClient = new WebClient();
myWebClient.Credentials=new NetworkCredential(username, password);
Console.WriteLine("\nPlease enter the fully qualified path of the file to be uploaded to the URI");
string fileName = Console.ReadLine();
Console.WriteLine("Uploading {0} to {1} ...",fileName,uriString);

// Upload the file to the URI.
// The 'UploadFile(uriString,fileName)' method implicitly uses HTTP POST method.
byte[] responseArray = myWebClient.UploadFile(uriString,fileName);