简体   繁体   中英

upload a XML file using FTP in c#

Please tell me how to upload a XML file using FTP in c#? Im currently using FtpWebRequest method and its giving me errors

my code is

//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();
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) { try { //Create a FTP Request Object and Specfiy a Complete Path // 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;
}  `

Here is my successfully working code to upload any file through FTP (I've written it in VB.NET but hopefully you can convert it to C# using any of the online translators)

    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

Here is the link to the entire article about developing this FTP Client:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM