2015-09-25 49 views
-1

我试图从以下链接下载csv文件,但在最后一行引发异常“路径错误中的非法字符”。我相信这是链接中的问号标志,会弄乱一切,但我必须得到它的工作..任何建议?路径错误c中的非法字符#

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); 
+0

你可以可以只用其他字符替换问号...... –

+2

问题标记是有效的url字符。 –

+0

此链接可能会有帮助:http://stackoverflow.com/questions/146134/how-to-remove-illegal-characters-from-path-and-filenames –

回答

1

确定。让我们看看你的代码。

// 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); 
     } 
    } 
} 
+0

非常感谢你! –

+0

欢迎您:) – aloisdg

3

这工作:

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); 
+0

不要忘记处理WebClient。看到我的答案。 – aloisdg

相关问题