[英]C# FTP The given path's format is not supported
这是我的代码,我有一个包含许多zip
文件的FTP。 每个zip文件都有一个具有相同名称的XML
。 我想解析这些xml文件。
我所做的是:
获取FTP中所有zip文件的列表,并将名称保存在此变量directories
。
现在,我想打开每个zip文件,其名称在directories
列表中。 我做到了
foreach (string fileNameInFTP in directories) { }
现在要读取该zip文件的内容,我尝试了以下操作:
string fileName = FTPAddress + fileNameInFTP; using (var file = File.OpenRead(fileName)) using (var zip = new ZipArchive(file, ZipArchiveMode.Read)) { foreach (var entry in zip.Entries) { using (var stream = entry.Open()) { // do whatever we want with stream // ... } } }
我收到此异常The given path's format is not supported.
在这一行上: using (var file = File.OpenRead("ftp://" +FTPAddress +"/" + fileNameInFTP))
您应该使用类似这样的方式,而不是尝试使用File.OpenRead进行远程FTP文件下载。
http://msdn.microsoft.com/zh-cn/library/ms229711%28v=vs.110%29.aspx
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.DownloadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
using (var zip = new ZipArchive(responseStream , ZipArchiveMode.Read))
{
//Loops through each file in the zip that has the ".xml" extension
foreach (var entry in zip.Entries.Where(x=> (Path.GetExtension(x.Name) ?? "").ToLower() ==".xml"))
{
using (var stream = entry.Open())
{
//Load xml file and do whatever you like with it.
var xmlDocument = XDocument.Load(stream);
}
}
}
Console.WriteLine("Download Complete, status {0}", response.StatusDescription);
response.Close();
您不能使用File
IO打开FTP流,这是如何使用.NET中的WebRequest
打开FTP的示例:
private static void Main(string[] args)
{
var ftp = WebRequest.Create(@"ftp://ftp.microsoft.com/softlib/MSLFILES/aspwebwiz2k.zip");
//ftp.Credentials=new NetworkCredential("anonymous","anonymous");
var response=ftp.GetResponse();
var stream=response.GetResponseStream();
var ms = ToMemoryStream(stream);
var archive = new ZipArchive(ms, ZipArchiveMode.Read);
var entry=archive.GetEntry("file name here");
var doc=XDocument.Load(entry.Open());
}
public static MemoryStream ToMemoryStream( Stream stream)
{
var memoryStream = new MemoryStream();
var buffer = new byte[4096];
while (true)
{
var readCount = stream.Read(buffer, 0, buffer.Length);
if (readCount == 0)
break;
memoryStream.Write(buffer, 0, readCount);
}
memoryStream.Position = 0;
return memoryStream;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.