我想从ftp远程目录中读取文件。每天我都将FTP文件夹放入100个文件之类的文件中,并且每天要读取所有文件并将数据推送到数据库。
但是,当我尝试读取文件时,出现错误:
System.NotSupportedException:'给定路径的格式不是 支持的。'
我的文件存储在ftp中,我尝试访问完整路径以读取文件,如示例所示:
ftp://dmo.someftpurl.ie:311/Directory-Test/in/demofile_measurement2020.xml
这是我到目前为止所做的(请阅读代码注释):
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml;
namespace FtpReader
{
class Program
{
static void Main(string[] args)
{
List<string> ftpFiles = new List<string>(); // List where I will store all file names
#region Credentials & Connection // Accessing FTP folder
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://dmo.someftpurl.ie:311/Directory-Test/in/");
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential("someUsername", "somePassword");
#endregion
#region Getting file lists from Ftp // Here I get list of all files available in ftp directory
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var line = reader.ReadLine();
while (line != null)
{
var split = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var fileName = split[split.Length - 1];
if (!string.IsNullOrWhiteSpace(fileName))
{
ftpFiles.Add(fileName);
}
line = reader.ReadLine();
}
}
}
#endregion
#region Reading file by file as XML // Here I've tried reading xml file from ftp directory
if(ftpFiles.Any())
{
foreach(var item in ftpFiles)
{
var item_path = "ftp://dmo.someftpurl.ie:311/Directory-Test/in/" + item; // ftp://dmo.someftpurl.ie:311/Directory-Test/in/demofile_measurement2020.xml
XmlDataDocument xmldoc = new XmlDataDocument();
XmlNodeList xmlnode;
string str = null;
FileStream fs = new FileStream(item_path, FileMode.Open, FileAccess.Read); // Here is where app breaks
xmldoc.Load(fs);
xmlnode = xmldoc.GetElementsByTagName("myCustomNode");
for (int i = 0; i <= xmlnode.Count - 1; i++)
{
}
}
}
#endregion
}
}
}
您正在使用带有FileStream对象的FTP文件URI,这是非法的。存储在item_path中的值必须是操作系统可以解析的路径字符串:
FileStream fs =新的FileStream(item_path,FileMode.Open,FileAccess.Read); //这是应用程序中断的地方