2011-05-23 46 views
8

我想從FTP服務器讀取文件而不將其下載到本地文件。我寫了一個功能,但它不工作:從FTP讀取文件到C#中的內存

private string GetServerVersion() 
{ 
    WebClient request = new WebClient(); 

    string url = FtpPath + FileName; 
    string version = ""; 

    request.Credentials = new NetworkCredential(ftp_user, ftp_pas); 

    try 
    { 
     byte[] newFileData = request.DownloadData(new Uri(FtpPath)+FileName); 
     string fileString = System.Text.Encoding.UTF8.GetString(newFileData); 
    } 
    catch (WebException e) 
    { 
    } 
    return version; 
} 
+0

它不起作用,你會得到什麼錯誤。你能打印更多的調試嗎? – ColWhi 2011-05-23 14:38:24

+1

你能描述它不工作的方式(包括例外細節,如果有的話)? – 2011-05-23 14:38:34

+1

不知道錯誤,很難建議。但是你在這個例子中返回一個空字符串? – 2011-05-23 14:45:24

回答

23

下面是使用你的代碼獲取從Microsoft公共FTP服務器的文件的簡單的工作示例:

WebClient request = new WebClient(); 
string url = "ftp://ftp.microsoft.com/developr/fortran/" +"README.TXT"; 
request.Credentials = new NetworkCredential("anonymous", "[email protected]"); 

try 
{ 
    byte[] newFileData = request.DownloadData(url); 
    string fileString = System.Text.Encoding.UTF8.GetString(newFileData); 
    Console.WriteLine(fileString); 
} 
catch (WebException e) 
{ 
    // Do something such as log error, but this is based on OP's original code 
    // so for now we do nothing. 
} 

我想你是在爲你的代碼在這裏失去了在這條線斜線:

string url = FtpPath + FileName; 

也許在FtpPathFileName之間?

+0

此代碼不必要地在內存中保留整個文件兩次。請使用'WebClient.DownloadString'代替[請參閱我的回答獲取更多信息](https://stackoverflow.com/a/47259033/850848)。 – 2017-11-13 07:27:25

0

這是不可能知道是什麼問題沒有對錯誤/異常的詳細信息。

在猜測,你似乎並不在最初宣佈

string version = ""; 

試着改變你的代碼

version = System.Text.Encoding.UTF8.GetString(newFileData); 
+0

現在我想讀取fileString的值,但我不能,以後我會從文件中獲取版本的值! – 2011-05-23 14:47:43

+0

錯誤在這裏:byte [] newFileData = request.DownloadData(new Uri(FtpPath)+ FileName);它不會返回一個值! – 2011-05-23 14:49:55

+0

Uri的結果是什麼?它應該是類似於「ftp:// ftp.yoursite.com/yourfile.txt」(刪除ftp後的空格://) – Jemes 2011-05-23 15:31:58

2

你有上面的代碼是非常後要分配一個新的值version simillar到另一個我在2天前發現和使用自己的Stackoverlow示例。如果您正確設置了URI,用戶和密碼,它將下載文件並將內容設置爲FileString。我不確定你想要在不下載的情況下閱讀文件是什麼意思。這不是一個真正的選擇。

如果您想查看文件屬性(我看到您提到「版本」),您可以使用下面的代碼從FTP服務器獲取所有文件的名稱,數據和大小,而無需下載文件。

調用GetFileInfo並傳入文件名(確保您按照代碼設置完整的FTP路徑,用戶和密碼)。這會給你一個帶有Name,Date和Size的FTPFileInfo對象。

public static FTPFileInfo GetFileInfo(string fileName) 
     { 
      var dirInfo = WordstockExport.GetFTPDirectoryDetails(); 
      var list = FTPFileInfo.Load(dirInfo); 
      try 
      { 
       FTPFileInfo ftpFile = list.SingleOrDefault(f => f.FileName == fileName); 
       return ftpFile; 
      } 
      catch { } 
      return null; 
     } 
    class FTPFileInfo 
     { 
      private DateTime _FileDate; 
      private long _FileSize; 
      private string _FileName; 

      public DateTime FileDate 
      { 
       get { return _FileDate; } 
       set { _FileDate = value; } 
      } 
      public long FileSize 
      { 
       get { return _FileSize; } 
       set { _FileSize = value; } 
      } 
      public string FileName 
      { 
       get { return _FileName; } 
       set { _FileName = value; } 
      } 

      public FTPFileInfo() { } 
      public static FTPFileInfo LoadFromLine(string line) 
      { 
       FTPFileInfo file = new FTPFileInfo(); 

       string[] ftpFileInfo = line.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); 
       file._FileDate = DateTime.Parse(ftpFileInfo[0] + " " + ftpFileInfo[1]); 
       file._FileSize = long.Parse(ftpFileInfo[2]); 
       file._FileName = ftpFileInfo[3]; 

       return file; 

      } 
      public static List<FTPFileInfo> Load(string listDirectoryDetails) 
      { 
       List<FTPFileInfo> files = new List<FTPFileInfo>(); 

       string[] lines = listDirectoryDetails.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); 
       foreach(var line in lines) 
        files.Add(LoadFromLine(line)); 

       return files; 
      } 

     } 
     private static string GetFTPDirectoryDetails() 
      { 
       FtpWebRequest request = (FtpWebRequest)WebRequest.Create(App.Export_FTPPath); 
       request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; 
       request.Credentials = new NetworkCredential(App.FTP_User, App.FTP_Password); 
       FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 

       Stream responseStream = response.GetResponseStream(); 
       StreamReader reader = new StreamReader(responseStream); 
       string fileLines = reader.ReadToEnd(); 
       reader.Close(); 
       response.Close(); 

       return fileLines; 
      } 
0

C Sharp GUI應用程序。最小的FTP傳輸,不優雅,但它工作正常。 GUI,而不是控制檯。

來自noaa的天氣。找到你的地區(尋找你的metar)! 一個METAR天氣報告,主要用於飛行員在飛行前

構建的一部分的履行與VS 2012 RC溢價(2012年7月)

(點擊標籤,而不是按鈕)

using System; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Net; 
using System.IO; 
using System.Collections.Generic; 

namespace getweather 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button2_Click(object sender, EventArgs e) 
     { 
      Application.Exit(); 
     } 

     private void CYYY_Click(object sender, EventArgs e) 
     { 
      WebClient request = new WebClient(); 
      string url = "ftp://tgftp.nws.noaa.gov/data/observations/metar/decoded/CYYY.TXT"; 
      request.Credentials = new NetworkCredential("anonymous", "[email protected]"); 
      byte[] newFileData = request.DownloadData(url); 
      string fileString = System.Text.Encoding.UTF8.GetString(newFileData); 
      richTextBox1.Text = fileString; 
     } 

     private void CYSC_Click(object sender, EventArgs e) 
     { 
      WebClient request = new WebClient(); 
      string url = "ftp://tgftp.nws.noaa.gov/data/observations/metar/decoded/CYSC.TXT"; 
      request.Credentials = new NetworkCredential("anonymous", "[email protected]"); 
      byte[] newFileData = request.DownloadData(url); 
      string fileString = System.Text.Encoding.UTF8.GetString(newFileData); 
      richTextBox1.Text = fileString; 

     } 

     private void CYQB_Click(object sender, EventArgs e) 
     { 
      WebClient request = new WebClient(); 
      string url = "ftp://tgftp.nws.noaa.gov/data/observations/metar/decoded/CYQB.TXT"; 
      request.Credentials = new NetworkCredential("anonymous", "[email protected]"); 
      byte[] newFileData = request.DownloadData(url); 
      string fileString = System.Text.Encoding.UTF8.GetString(newFileData); 
      richTextBox1.Text = fileString; 

     } 

     private void CYUY_Click(object sender, EventArgs e) 
     { 
      WebClient request = new WebClient(); 
      string url = "ftp://tgftp.nws.noaa.gov/data/observations/metar/decoded/CYUY.TXT"; 
      request.Credentials = new NetworkCredential("anonymous", "[email protected]"); 
      byte[] newFileData = request.DownloadData(url); 
      string fileString = System.Text.Encoding.UTF8.GetString(newFileData); 
      richTextBox1.Text = fileString; 

     } 

     private void CYHU_Click(object sender, EventArgs e) 
     { 
      WebClient request = new WebClient(); 
      string url = "ftp://tgftp.nws.noaa.gov/data/observations/metar/decoded/CYHU.TXT"; 
      request.Credentials = new NetworkCredential("anonymous", "[email protected]"); 
      byte[] newFileData = request.DownloadData(url); 
      string fileString = System.Text.Encoding.UTF8.GetString(newFileData); 
      richTextBox1.Text = fileString; 

     } 
    } 
} 
-1

我們可以使用下面的方法從ftp獲取文件屬性而不下載文件。這對我來說工作得很好。

public DataTable getFileListFTP(string serverIP,string userID,string Password) 
    { 
     DataTable dt = new DataTable(); 
     string[] fileListArr; 
     string fileName = string.Empty; 
     long fileSize = 0; 
     // DateTime creationDate; 
     string creationDate; 

     FtpWebRequest Request = (FtpWebRequest)WebRequest.Create(serverIP); 
     Request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; 
     Request.Credentials = new NetworkCredential(userID,Password); 
     FtpWebResponse Response = (FtpWebResponse)Request.GetResponse(); 
     Stream ResponseStream = Response.GetResponseStream(); 
     StreamReader Reader = new StreamReader(ResponseStream); 
     dt.Columns.Add("FileName", typeof(String)); 
     dt.Columns.Add("FileSize", typeof(String)); 
     dt.Columns.Add("CreationDate", typeof(DateTime)); 
     //CultureInfo c = new CultureInfo("ES-ES"); 
     while (!Reader.EndOfStream)//Read file name 
     { 
      fileListArr = Convert.ToString(Reader.ReadLine()).Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); 
      fileSize = long.Parse(fileListArr[4]); 
      creationDate = fileListArr[6] + " " + fileListArr[5] + " " + fileListArr[7]; 
      //creationDate =Convert.ToDateTime(fileListArr[6] + " " + fileListArr[5] + " " + fileListArr[7], c).ToString("dd/MMM/yyyy", DateTimeFormatInfo.InvariantInfo); 
      fileName = Convert.ToString(fileListArr[8]); 

      DataRow drow = dt.NewRow(); 
      drow["FileName"] = fileName; 
      drow["FileSize"] = fileName; 
      drow["CreationDate"] = creationDate; 
      dt.Rows.Add(drow); 
     } 
     Response.Close(); 
     ResponseStream.Close(); 
     Reader.Close(); 
     return dt; 
    } 
0
WebClient request = new WebClient(); 
string url = "ftp://ftp.microsoft.com/developr/fortran/" +"README.TXT"; 
request.Credentials = new NetworkCredential("anonymous", "[email protected]"); 
request.Proxy = null; 

try 
{ 
    byte[] newFileData = request.DownloadData(url); 
    string fileString = System.Text.Encoding.UTF8.GetString(newFileData); 
    Console.WriteLine(fileString); 
} 
catch (WebException e) 
{ 
    // Do something such as log error, but this is based on OP's original code 
    // so for now we do nothing. 
} 
0

我知道這是一個老問題,但我想我會建議使用path.combine下一個傢伙閱讀本。幫助清理這些問題。

 string url = Path.Combine("ftp://ftp.microsoft.com/developr/fortran", "README.TXT"); 
-3

看看我的FTP類,它可能正是你需要的。

Public Class FTP 
     '-------------------------[BroCode]-------------------------- 
     '----------------------------FTP----------------------------- 
     Private _credentials As System.Net.NetworkCredential 
     Sub New(ByVal _FTPUser As String, ByVal _FTPPass As String) 
      setCredentials(_FTPUser, _FTPPass) 
     End Sub 
     Public Sub UploadFile(ByVal _FileName As String, ByVal _UploadPath As String) 
      Dim _FileInfo As New System.IO.FileInfo(_FileName) 
      Dim _FtpWebRequest As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(New Uri(_UploadPath)), System.Net.FtpWebRequest) 
      _FtpWebRequest.Credentials = _credentials 
      _FtpWebRequest.KeepAlive = False 
      _FtpWebRequest.Timeout = 20000 
      _FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile 
      _FtpWebRequest.UseBinary = True 
      _FtpWebRequest.ContentLength = _FileInfo.Length 
      Dim buffLength As Integer = 2048 
      Dim buff(buffLength - 1) As Byte 
      Dim _FileStream As System.IO.FileStream = _FileInfo.OpenRead() 
      Try 
       Dim _Stream As System.IO.Stream = _FtpWebRequest.GetRequestStream() 
       Dim contentLen As Integer = _FileStream.Read(buff, 0, buffLength) 
       Do While contentLen <> 0 
        _Stream.Write(buff, 0, contentLen) 
        contentLen = _FileStream.Read(buff, 0, buffLength) 
       Loop 
       _Stream.Close() 
       _Stream.Dispose() 
       _FileStream.Close() 
       _FileStream.Dispose() 
      Catch ex As Exception 
       MessageBox.Show(ex.Message, "Upload Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error) 
      End Try 
     End Sub 
     Public Sub DownloadFile(ByVal _FileName As String, ByVal _ftpDownloadPath As String) 
      Try 
       Dim _request As System.Net.FtpWebRequest = System.Net.WebRequest.Create(_ftpDownloadPath) 
       _request.KeepAlive = False 
       _request.Method = System.Net.WebRequestMethods.Ftp.DownloadFile 
       _request.Credentials = _credentials 
       Dim _response As System.Net.FtpWebResponse = _request.GetResponse() 
       Dim responseStream As System.IO.Stream = _response.GetResponseStream() 
       Dim fs As New System.IO.FileStream(_FileName, System.IO.FileMode.Create) 
       responseStream.CopyTo(fs) 
       responseStream.Close() 
       _response.Close() 
      Catch ex As Exception 
       MessageBox.Show(ex.Message, "Download Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error) 
      End Try 
     End Sub 
     Public Function GetDirectory(ByVal _ftpPath As String) As List(Of String) 
      Dim ret As New List(Of String) 
      Try 
       Dim _request As System.Net.FtpWebRequest = System.Net.WebRequest.Create(_ftpPath) 
       _request.KeepAlive = False 
       _request.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails 
       _request.Credentials = _credentials 
       Dim _response As System.Net.FtpWebResponse = _request.GetResponse() 
       Dim responseStream As System.IO.Stream = _response.GetResponseStream() 
       Dim _reader As System.IO.StreamReader = New System.IO.StreamReader(responseStream) 
       Dim FileData As String = _reader.ReadToEnd 
       Dim Lines() As String = FileData.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries) 
       For Each l As String In Lines 
        ret.Add(l) 
       Next 
       _reader.Close() 
       _response.Close() 
      Catch ex As Exception 
       MessageBox.Show(ex.Message, "Directory Fetch Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error) 
      End Try 
      Return ret 
     End Function 

     Private Sub setCredentials(ByVal _FTPUser As String, ByVal _FTPPass As String) 
      _credentials = New System.Net.NetworkCredential(_FTPUser, _FTPPass) 
     End Sub 
    End Class 

初始化:

Dim ftp As New FORM.FTP("username", "password") 

ftp.UploadFile("c:\file.jpeg", "ftp://domain/file.jpeg") 

ftp.DownloadFile("c:\file.jpeg", "ftp://ftp://domain/file.jpeg") 

Dim directory As List(Of String) = ftp.GetDirectory("ftp://ftp.domain.net/") 
     ListBox1.Items.Clear() 
     For Each item As String In directory 
      ListBox1.Items.Add(item) 
     Next 

https://stackoverflow.com/a/28669746/2701974

+1

OP沒有要求VB – mwilson 2015-11-26 02:37:42

0

如果該文件是小的,最簡單的方法是使用WebClient.DownloadData

WebClient client = new WebClient(); 
string url = "ftp://ftp.example.com/remote/path/file.zip"; 
client.Credentials = new NetworkCredential("username", "password"); 
byte[] contents = client.DownloadData(url); 

如果文件是文本文件,使用WebClient.DownloadString

string contents = client.DownloadString(url); 

它假定文件內容是UTF-8編碼(一個普通的ASCII文件將做太多)。如果您需要使用不同的編碼,請使用WebClient.Encoding property


如果文件較大,因此,你需要的而不是將其加載到內存整體來處理它在塊,使用FtpWebRequest

FtpWebRequest request = 
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip"); 
request.Credentials = new NetworkCredential("username", "password"); 
request.Method = WebRequestMethods.Ftp.DownloadFile; 

using (Stream stream = request.GetResponse().GetResponseStream()) 
{ 
    byte[] buffer = new byte[10240]; 
    int read; 
    while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) 
    { 
     // process the chunk in "buffer" 
    } 
} 

如果大文件是文本文件,並且您想要按行處理它,而不是使用固定大小的塊,請使用StreamReader

FtpWebRequest request = 
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.txt"); 
request.Credentials = new NetworkCredential("username", "password"); 
request.Method = WebRequestMethods.Ftp.DownloadFile; 

using (Stream stream = request.GetResponse().GetResponseStream()) 
using (StreamReader reader = new StreamReader(stream)) 
{ 
    while (!reader.EndOfStream) 
    { 
     string line = reader.ReadLine(); 
     // process the line 
     Console.WriteLine(line); 
    } 
} 

再次,這個假定UTF-8編碼。如果您想使用其他編碼,請使用overload of StreamReader contructor that takes also Encoding