簡體   English   中英

將文本框上載到ftp C#上的文本文件中

[英]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塊。
  • 在UI線程上進行這樣的網絡訪問是一個壞主意。 在發生FTP請求時,UI線程將阻塞(因此整個UI會掛起)。 請改用后台線程。

要上傳文件,您需要使用FtpWebRequest類。

引用:

使用FtpWebRequest對象將文件上載到服務器時,必須將文件內容寫入通過調用GetRequestStream方法或它的異步對應對象BeginGetRequestStreamEndGetRequestStream方法獲得的請求流中。 在發送請求之前,您必須寫入流並關閉流。

有關上傳文件的示例(您可以更改為寫入示例中的流內容), 請參見此處

取自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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM