I'm trying to write a random wallpaper downloader for my desktop. The code works fine on the first download, but hangs and throws an exception on the second attempt. I tried to dipose of the client and sta开发者_Python百科rt with a fresh Web Client. I also tried without disposing. Thanks in advance.
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
}
}
}
Try changing the file name. It's quite likely that either pic.jpg or pic.bmp still have file locks on them when you are trying the second time. Pick a more unique file name each time.
Client.DownloadFile(pathStart + randomFile + pathEnd, "pic.jpg");
Probably failing to overwrite pic.jpg. For a test try incrementing the number at during the loop (pic1, pic2, etc.). You can always come up with a better naming scheme later.
精彩评论