2015-11-01 44 views
0

這傢伙的代碼存儲在FTP文件。任何一個可以重新配置此代碼,以便它存儲在RichTextBox的Windows窗體我在RichTextBox中寫任何東西的內容,當我點擊按鈕,就應該直接存儲FTP。如何將richtextbox內容直接存儲到C#中的ftp?

{ 
    Stream requestStream = null; 
    FileStream fileStream = null; 
    FtpWebResponse uploadResponse = null; 
    try 
    { 
     uploadUrl = "ftp://ftp.personalwebars.com/ATM/"; 
     fileName = txtTitle.Text + ".txt"; 
     FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(uploadUrl + @"/" + fileName); 
     uploadRequest.Method = WebRequestMethods.Ftp.UploadFile; 
     //Since the FTP you are downloading to is secure, send 
     //in user name and password to be able upload the file 
     ICredentials credentials = new NetworkCredential(user, pswd); 
     uploadRequest.Credentials = credentials; 
     //UploadFile is not supported through an Http proxy 
     //so we disable the proxy for this request. 
     uploadRequest.Proxy = null; 
     //uploadRequest.UsePassive = false; <--found from another forum and did not make a difference 
     requestStream = uploadRequest.GetRequestStream(); 

     byte[] buffer = new byte[1024]; 
     int bytesRead; 
     while (true) 
     { 
      bytesRead = fileStream.Read(buffer, 0, buffer.Length); 
      if (bytesRead == 0) 
       break; 
      requestStream.Write(buffer, 0, bytesRead); 
     } 
     //The request stream must be closed before getting 
     //the response. 
     requestStream.Close(); 
     uploadResponse = 
      (FtpWebResponse)uploadRequest.GetResponse(); 
     lblAuthentication.Text = "Your solution has been submitted in txt Mode. Thank You"; 
    } 
    catch (WebException ex) 
    { 

    } 
    finally 
    { 
     if (uploadResponse != null) 
      uploadResponse.Close(); 
     if (fileStream != null) 
      fileStream.Close(); 
     if (requestStream != null) 
      requestStream.Close(); 
    } 
} 
+2

你要找的'StreamWriter'。 – SLaks

回答

1

試試這個,從文本框提取字符串,並把它作爲內容的參數,

public void Send(string url, string fileName, string content, string user, string password) 
{ 
    byte[] bytes = Encoding.ASCII.GetBytes(content) 
    var request = (FtpWebRequest) WebRequest.Create(new Uri(url + @"/" + fileName)); 
    request.Method = WebRequestMethods.Ftp.UploadFile; 
    request.UsePassive = false; 
    request.Credentials = new NetworkCredential(user, password); 
    request.ContentLength = bytes.Length; 
    var requestStream = request.GetRequestStream(); 
    requestStream.Write(bytes, 0, bytes.Length); 
    requestStream.Close(); 
    var response = (FtpWebResponse) request.GetResponse(); 
    if (response != null) response.Close(); 
} 
相關問題