[英]Uploading a text box into a text file on an ftp C#
我正在嘗試將多行文本框流式傳輸到ftp服務器上的文本文件中。 有人可以告訴我哪里可能出問題了嗎?
private void btnSave_Click(object sender, EventArgs e)
{
UriBuilder b = new UriBuilder();
b.Host = "ftp.myserver.com";
b.UserName = "user";
b.Password = "pass";
b.Port = 21;
b.Path = "/myserver.com/directories/" + selected + ".txt";
b.Scheme = Uri.UriSchemeFtp;
Uri g = b.Uri;
System.Net.FtpWebRequest c = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(g);
c.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
System.Net.FtpWebResponse d = (System.Net.FtpWebResponse)c.GetResponse();
System.IO.Stream h = d.GetResponseStream;
System.IO.StreamWriter SW = new System.IO.StreamWriter(h);
String[] contents = textBox1.Lines.ToArray();
for (int i = 0; i < contents.Length; i++)
{
SW.WriteLine(contents[i]);
}
h.Close();
SW.Close();
d.Close();
}
我得到的錯誤是這一行:
System.IO.StreamWriter SW =新的System.IO.StreamWriter(h);
流不可寫。
有任何想法嗎?
FTP站點的響應流是從站點到您的數據。 您需要請求流...但是然后,您將不需要DownloadFile
方法-您沒有在下載,而是在上傳,所以您需要UploadFile
方法。
另外:
using
塊。 要上傳文件,您需要使用FtpWebRequest
類。
引用:
使用FtpWebRequest對象將文件上載到服務器時,必須將文件內容寫入通過調用
GetRequestStream
方法或它的異步對應對象BeginGetRequestStream
和EndGetRequestStream
方法獲得的請求流中。 在發送請求之前,您必須寫入流並關閉流。
有關上傳文件的示例(您可以更改為寫入示例中的流內容), 請參見此處 。
取自MSDN,並稍作修改:
public static bool UploadFileOnServer(string fileName, Uri serverUri)
{
// The URI described by serverUri should use the ftp:// scheme.
// It contains the name of the file on the server.
// Example: ftp://contoso.com/someFile.txt.
// The fileName parameter identifies the file
// to be uploaded to the server.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.UploadFile;
StreamReader sourceStream = new StreamReader(fileName);
byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse) request.GetResponse();
Console.WriteLine("Upload status: {0}",response.StatusDescription);
response.Close();
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.