我正在一些小應用程序工作,並需要上傳文本文件到FTP。從文本框傳遞文件名到WebRequest.Create在C#
我使用此代碼上傳文件:
using System;
using System;
using System.IO;
using System.Net;
using System.Text;
/// <summary>
/// Simple static class for uploading a file to an FTP server.
/// </summary>
public static class fileUpload
{
public static string uploadFile(string file)
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.mywebserver.com/myfile.txt");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("username", "password");
// Copy the entire contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(file);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
// Upload the file stream to the server.
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
// Get the response from the FTP server.
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
// Close the connection = Happy a FTP server.
response.Close();
// Return the status of the upload.
return response.StatusDescription;
}
}
要上傳文件我用這個:
fileUpload.uploadFile(uploadedfile.txt);
問題是當上傳的文件總是被命名爲我們myfile.txt的,我需要該文件的名稱與textBox1中的文本完全相同。
因此,例如我在硬盤上保存文件時使用這個("C:/savehere/"+textBox1.text +".txt");
它工作正常。
但是當我做同樣的位置:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.mywebserver.com/"+ textBox1.text + ".txt");
它不會工作。
我該如何在這個例子中做同樣的事情?
謝謝!
當我這樣做,它與一個錯誤回來:錯誤一個對象引用是所必需的非靜態字段,方法或屬性「 WindowsFormsApplication1.Form1.textBox7' – zero4 2015-02-06 20:16:59
據我所知,這是由於靜態,但我不知道如何將其更改爲正確的類型:( – zero4 2015-02-06 20:23:45