通过C Sharp中的FTP上传PDF文件
本文关键字:上传 PDF 文件 FTP 中的 Sharp 通过 | 更新日期: 2023-09-27 18:27:57
我有以下代码可以通过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;
}
我的问题是它只上传文本而不上传图像。我怎么能在不阅读的情况下上传文件?我的意思是,我只想选择并重命名文件并上传它。
使用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);