在c#中使用FTP上传XML文件

时间:2012-02-14 13:17:12

标签: c# xml file-upload ftp

请告诉我如何在c#中使用FTP上传XML文件?我目前正在使用FtpWebRequest方法,它给我错误

我的代码是

//Create FTP request
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://www.itsthe1.com/profiles/nuwan/sample.txt");

request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(Username, Password);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;

//Load the file
FileStream stream = File.OpenRead(@"C:\sample.txt");
byte[] buffer = new byte[stream.Length];

stream.Read(buffer, 0, buffer.Length);
stream.Close();

//Upload file
Stream reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();

2 个答案:

答案 0 :(得分:0)

这是我成功运行的代码,通过FTP上传任何文件(我用VB.NET编写,但希望你可以使用任何在线翻译器将其转换为C#)

    Public Function Upload(ByVal fi As FileInfo, Optional ByVal targetFilename As String = "") As Boolean
    'copy the file specified to target file: target file can be full path or just filename (uses current dir)
    '1. check target
    Dim target As String
    If targetFilename.Trim = "" Then
        'Blank target: use source filename & current dir
        target = GetCurrentUrl() & "/" & fi.Name
    Else
        'otherwise treat as filename only, use current directory
        target = GetCurrentUrl() & "/" & targetFilename
    End If
    Dim URI As String = target 'GetCurrentUrl() & "/" & target
    'perform copy
    Dim ftp As Net.FtpWebRequest = GetRequest(URI)
    'Set request to upload a file in binary
    ftp.Method = Net.WebRequestMethods.Ftp.UploadFile
    ftp.UseBinary = True
    'Notify FTP of the expected size
    ftp.ContentLength = fi.Length
    'create byte array to store: ensure at least 1 byte!
    Const BufferSize As Integer = 2048
    Dim content(BufferSize - 1) As Byte, dataRead As Integer
    'open file for reading
    Using fs As FileStream = fi.OpenRead()
        Try
            'open request to send
            Using rs As Stream = ftp.GetRequestStream
                Dim totBytes As Long = 0
                Do
                    dataRead = fs.Read(content, 0, BufferSize)
                    rs.Write(content, 0, dataRead)
                    totBytes += dataRead
                    RaiseEvent StatusChanged(totBytes.ToString() & " bytes sent...")
                Loop Until dataRead < BufferSize
                rs.Close()
                RaiseEvent StatusChanged("File uploaded successfully")
            End Using
        Catch ex As Exception
            RaiseEvent StatusChanged("Error: " & ex.Message)
        Finally
            'ensure file closed
            fs.Close()
        End Try
    End Using
    ftp = Nothing
    Return True
End Function

以下是有关开发此FTP客户端的整篇文章的链接:

http://dot-net-talk.blogspot.com/2008/12/how-to-create-ftp-client-in-vbnet.html

答案 1 :(得分:0)

protected void Button1_Click(object sender, EventArgs e)
{ 
    string server = "-------"; //your ip address
    string ftpPath = "ftp://" + server + "//Files//" +FileUpload1.FileName;
    string uname = "-----";
    string password = "----------";
    string filePath = Server.MapPath("~") + "\\" + FileUpload1.FileName;
     try
     {
         UploadToFTP(ftpPath,filePath,uname,password);  

     }
     catch (Exception ex)
     {
        //logic here

     }       

}

`private bool UploadToFTP(string strFTPFilePath,string strLocalFilePath,string strUserName,string strPassword)     {         尝试         {           //创建FTP请求对象并指定完整路径           // System.Net.WebRequest.Create(strFTPFilePath);           FtpWebRequest reqObj =(FtpWebRequest)WebRequest.Create(strFTPFilePath);

        //Call A FileUpload Method of FTP Request Object
        reqObj.Method = WebRequestMethods.Ftp.UploadFile;

        //If you want to access Resourse Protected,give UserName and PWD
        reqObj.Credentials = new NetworkCredential(strUserName, strPassword);

        // Copy the contents of the file to the byte array.
        byte[] fileContents = File.ReadAllBytes(strLocalFilePath);
        reqObj.ContentLength = fileContents.Length;

        //Upload File to FTPServer
        Stream requestStream = reqObj.GetRequestStream();
      //  Stream requestStream = response.GetResponseStream();
        requestStream.Write(fileContents, 0, fileContents.Length);
        requestStream.Close();
        FtpWebResponse response = (FtpWebResponse)reqObj.GetResponse();
        response.Close();
        Label1.Text = "File Transfered Completed" + response.StatusDescription;
    }

    catch (Exception Ex)
    {
        throw Ex;
    }
    return true;
}  `