2015-09-25 50 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

相關問題