C# 将文件名从textBox传递到WebRequest.Create#

C# 将文件名从textBox传递到WebRequest.Create#,c#,file,C#,File,我正在开发一些小应用程序,需要上传一个文本文件到ftp 我使用此代码上载文件: 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

我正在开发一些小应用程序,需要上传一个文本文件到ftp

我使用此代码上载文件:

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);
当上传的文件总是名为us myfile.txt时,问题就出现了,我需要文件名与textBox1中的文本完全相同

例如,我在硬盘
上保存文件时使用了这个选项(“C:/savehere/”+textBox1.text+“.txt”)
而且效果很好

但当我在这里做同样的事情时:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.mywebserver.com/"+ textBox1.text + ".txt"); 
这行不通

在这个例子中,我如何做同样的事情


谢谢大家!

如果路径为
ftp://www.mywebserver.com/filename.txt

试着换成

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.mywebserver.com/%2f"+ textBox1.text + ".txt");
但是,最好创建一个目录来保存这些文件

ftp://www.mywebserver.com/%2ftemp/filename.txt

更新--


当我这样做时,它返回一个错误:错误1非静态字段、方法或属性“WindowsFormsApplication1.Form1.textBox7”需要对象引用


我知道这是由于静态造成的,但我不知道如何将其更改为正确的类型:(

怎么样

string baseUrl = "ftp://www.mywebserver.com/";
string FileName = textBox1.Text;
string extension = ".txt";

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(new Uri(baseUrl), string.Format("{0}{1}", FileName, extension)));
这将导致:

ftp://www.mywebserver.com/{textboxContent}.txt

当我这样做时,它返回一个错误:错误1非静态字段、方法或属性“WindowsFormsApplication1.Form1.textBox7”需要一个对象引用。我知道这是由静态引起的,但我不知道如何将其更改为正确的类型:(
ftp://www.mywebserver.com/{textboxContent}.txt