загрузить файл XML, используя FTP в c # - PullRequest
1 голос
/ 14 февраля 2012

Скажите, пожалуйста, как загрузить файл XML с использованием FTP в c #?Я в настоящее время использую метод 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 голосов
/ 31 октября 2012
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 (строка strFTPFilePath, строка strLocalFilePath, строка strUserName, строка strPassword) {try {// Создать объект запроса 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;
}  `
0 голосов
/ 16 февраля 2012

Вот мой успешно работающий код для загрузки любого файла через 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

...