在C Sharp中通过FTP上传PDF文件

时间:2012-03-16 13:54:16

标签: c# winforms pdf ftp

我有以下代码通过ftp上传pdf文件:

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;
        }

我的问题是它只上传没有图片的文字。如何在不读取文件的情况下上传文件?我的意思是我只想选择并重命名该文件并将其上传。

1 个答案:

答案 0 :(得分:2)

使用WebClient类,然后使用UploadFile方法。 来自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);