2010-01-22 111 views
0

我試圖爲我的桌面編寫一個隨機壁紙下載程序。 代碼在第一次下載時工作正常,但在 第二次嘗試中掛起並引發異常。我試圖介紹客戶端,並從新的Web客戶端開始。 我也試過沒有處置。提前致謝。WebClient在第二次下載嘗試時拋出異常

public class ChangeWallpaper 
{ 
    [DllImport("user32.dll", CharSet = CharSet.Auto)] 
    static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni); 

    public static void Main() 
    { 
     Random fileNumber = new Random(); 

     string pathStart = "http://www.starcraft2.com/images/screenshots/ss"; 
     string pathEnd = "-hires.jpg"; 

     while (true) //forever loop 
     { 
      string randomFile = fileNumber.Next(1, 126).ToString(); 

      WebClient Client = new WebClient(); 

      //OK FIRST TIME -> THROWS EXCEPTION ON SECOND ATTEMPT! 
      Client.DownloadFile(pathStart + randomFile + pathEnd, "pic.jpg"); 

      Client.Dispose(); //tried removing 

      Bitmap bm = new Bitmap(Image.FromFile("pic.jpg")); 
      bm.Save("pic.bmp", ImageFormat.Bmp); 
      bm.Dispose(); //tried removing - no help 
      SystemParametersInfo(20, 0, "pic.bmp", 0x01 | 0x02); 
      Thread.Sleep(60000); // Sleep for 1 minute 
     } 
    } 
} 
+1

...和例外是? – 2010-01-22 20:31:56

+0

異常的性質是什麼? – 2010-01-22 20:32:36

+0

顯示異常。如果您刪除了SystemParametersInfo調用,您是否也會遇到異常? – nos 2010-01-22 20:33:22

回答

2

請嘗試更改文件名。當你第二次嘗試的時候,pic.jpg或者pic.bmp很可能仍然有文件鎖定。每次選擇一個更獨特的文件名稱。

Client.DownloadFile(pathStart + randomFile + pathEnd, "pic.jpg"); 

可能沒有覆蓋pic.jpg。對於測試,嘗試在循環過程中增加數字(圖片1,圖片2等)。以後你總是可以想出一個更好的命名方案。

+0

工作。它掛在文件上。 我不希望有很多僱用圖片文件。 我可以以某種方式釋放文件鎖嗎? 謝謝 – Greycrow 2010-01-22 20:42:41

相關問題