路径错误中的非法字符

本文关键字:非法 字符 错误 路径 | 更新日期: 2023-09-27 18:14:36

我试图从以下链接下载csv文件,但在最后一行抛出了一个异常"路径错误中的非法字符"。我相信是链接中的问号把一切都搞砸了,但我必须让它工作。有什么建议吗?

string remoteUri = "download.finance.yahoo.com/d/quotes.csv?s=%40%5EDJI,aapl&f=o&e=.csv";
string fileName = "aapl.csv", myStringWebResource = null;
// Create a new WebClient instance.
WebClient myWebClient = new WebClient();
// Concatenate the domain with the Web resource filename.
myStringWebResource = remoteUri + fileName;
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource, fileName);

路径错误中的非法字符

这行得通:

string remoteUri = @"http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EDJI,aapl&f=o&e=.csv";
string fileName = @"c:'aapl.csv";
// Create a new WebClient instance.
WebClient myWebClient = new WebClient();       
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(remoteUri, fileName);

好的。让我们看看你的代码。

// Dont forget the "http://". A lot of browser add it themselves but the WebClient doesnt.
string remoteUri = "download.finance.yahoo.com/d/quotes.csv?s=%40%5EDJI,aapl&f=o&e=.csv";
// I recommend to take the habitude to write each one in one line.
string fileName = "aapl.csv", myStringWebResource = null;
// Use the "using" keyword to dispose WebClient
WebClient myWebClient = new WebClient();
// Why are you doing this? Your url is working without. No need to concat here.
myStringWebResource = remoteUri + fileName;
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource, fileName);

测试的解决方案:(在.NETFiddle上演示)

using System;
using System.Net;
public class Program
{
    public void Main()
    {
        string remoteUri = "http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EDJI,aapl&f=o&e=.csv";
        using (var myWebClient = new WebClient())
        {
            string csv = myWebClient.DownloadString(remoteUri);
            Console.WriteLine(csv);
        }   
    }
}

解决你的问题:

using System;
using System.Net;
public class Program
{
    public void Main()
    {
        string remoteUri = "http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EDJI,aapl&f=o&e=.csv";
        string fileName = "aapl.csv";
        using (var myWebClient = new WebClient())
        {
            myWebClient.DownloadFile(remoteUri, fileName);
        }   
    }
}