[英]How to upload file to ftp server in metro app using c#
我想使用C#在Metro應用程序中將文件上傳到FTP服務器。 我嘗試了這個,但是沒有用。
我在這里創建的是將.png小文件上傳到服務器,但無法正常工作。
public static async Task<bool> UpLoad(string localsubfolders, string ftpURIInfo, string Username, string Password, string filename)
{
bool Successful = false;
try
{
BackgroundUploader uploader = new BackgroundUploader();
StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile sampleFile = await storageFolder.GetFileAsync("wp_ss_20150313_0001.png");
Uri urlWithCredential;
bool Success = Uri.TryCreate(ftpURIInfo + "" + filename, UriKind.Absolute, out urlWithCredential);
if (!string.IsNullOrEmpty(Username.Trim()) &&
!string.IsNullOrEmpty(Password.Trim()))
{
urlWithCredential = new Uri(urlWithCredential.ToString().ToLower().Replace(@"ftp://",
string.Format(@"ftp://{0}:{1}@",
Username,
Password)));
}
UploadFile(urlWithCredential, sampleFile);
}
catch (Exception)
{
throw;
}
return Successful;
}
public static async Task UploadFile(Uri destination, StorageFile targetFile)
{
var request = WebRequest.Create(destination);
request.Credentials = Credentials;
request.Method = "STOR";
try
{
using (var requestStream = (await request.GetRequestStreamAsync()))
using (var stream = await targetFile.OpenStreamForReadAsync())
{
stream.CopyTo(requestStream);
}
}
catch { }
}
我找到這個問題的解決方案
以下代碼工作正常。
public static async Task<bool> SmallUpload1(string ftpURIInfo, string filename, string username, string password)
{
string serverUrl;
Uri serverUri = null;
//StorageFolder localFolderArea;
NetworkCredential credential;
bool Successful = false;
try
{
StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile targetFile = await storageFolder.GetFileAsync("wp_ss_20150313_0001.png");
Uri.TryCreate(ftpURIInfo, UriKind.Absolute, out serverUri);
serverUrl = serverUri.ToString();
credential = new System.Net.NetworkCredential(username.Trim(),
password.Trim());
WebRequest request = WebRequest.Create(serverUrl + "/" + filename);
request.Credentials = credential;
request.Proxy = WebRequest.DefaultWebProxy;
//STOR is for ftp: // POST is for http:// web sites
request.Method = "STOR";
byte[] buffer = Encoding.UTF8.GetBytes(UploadLine);
using (Stream requestStream = await request.GetRequestStreamAsync())
{
using (var stream = await targetFile.OpenStreamForReadAsync())
{
stream.CopyTo(requestStream);
}
}
Successful = true;
}
catch (Exception)
{
throw;
}
return Successful;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.