0

我正在编写一个小程序来自动更改桌面壁纸,来自在线图片库(imgur)。目前我有这个代码:

namespace Imgur_Wallpapers
{
    public partial class Form1 : Form
    {
        //IMGUR API = 3f1e4339e7bad35ff801bf76e369ae17

        private int Count = 1;

        public Form1()
        {
            InitializeComponent();
            timer1.Enabled = false;
            if (!File.Exists("image_black"))
            {
                Bitmap black = new Bitmap(10, 10);
                black.Save("transitionpaper.bmp");
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            DownloadFromImgur download = new DownloadFromImgur("gjZEc", Path.GetDirectoryName(Application.StartupPath));
            Wallpaper.Set(new Uri(Application.StartupPath + "/Image.bmp"), Wallpaper.Style.Centered);
            Count++;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            DownloadFromImgur download = new DownloadFromImgur(imgurAlbumIdBox.Text, Path.GetDirectoryName(Application.StartupPath));

            Wallpaper.Set(new Uri(Application.StartupPath + "/Image.bmp"), Wallpaper.Style.Centered);
            Count++;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            timer1.Interval = (int)whenToRefreshBox.Value;
            timer1.Enabled = true;
        }
    }

        private string url;
        public List<string> hash;
        private Random random;
        private string albumID;


        public DownloadFromImgur(string albumID, string folderToSaveTo)
        {
            try
            {
                this.albumID = albumID;
                hash = new List<string>();
                random = new Random();
                GetWebSite();
                Wallpaper.Set(new Uri(Application.StartupPath + "/transitionpaper.bmp"), Wallpaper.Style.Centered);
                WebClient client = new WebClient();
                File.Delete(Application.StartupPath + "/Image.bmp");
                client.DownloadFile(url, Application.StartupPath +  "/Image.bmp");
                client.Dispose();
            }
            catch (WebException ex)
            {

            }
        }

        private void GetWebSite()
        {
            var doc = XDocument.Load("http://api.imgur.com/2/album/" + albumID);

            hash.Clear();
            RecursiveWrite(doc.Root);

            url = hash[random.Next(hash.Count - 1)];
        }

        private void RecursiveWrite(XElement node)
        {
            foreach (var attribute  in node.Value)
            {
                if (node.Name == "original")
                {
                    hash.Add(node.Value);
                    break;
                }
            }

            foreach (var child in node.Elements())
            {
                RecursiveWrite(child);
            }
        }
    }

    public sealed class Wallpaper
    {
        Wallpaper() { }

        const int SPI_SETDESKWALLPAPER = 20;
        const int SPIF_UPDATEINIFILE = 0x01;
        const int SPIF_SENDWININICHANGE = 0x02;

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

        public enum Style : int
        {
            Tiled,
            Centered,
            Stretched
        }

        public static void Set(Uri uri, Style style)
        {
            System.IO.Stream s = new System.Net.WebClient().OpenRead(uri.ToString());

            System.Drawing.Image img = System.Drawing.Image.FromStream(s);
            string tempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp");
            img.Save(tempPath, System.Drawing.Imaging.ImageFormat.Bmp);

            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
            if (style == Style.Stretched)
            {
                key.SetValue(@"WallpaperStyle", 2.ToString());
                key.SetValue(@"TileWallpaper", 0.ToString());
            }

            if (style == Style.Centered)
            {
                key.SetValue(@"WallpaperStyle", 1.ToString());
                key.SetValue(@"TileWallpaper", 0.ToString());
            }

            if (style == Style.Tiled)
            {
                key.SetValue(@"WallpaperStyle", 1.ToString());
                key.SetValue(@"TileWallpaper", 1.ToString());
            }

            SystemParametersInfo(SPI_SETDESKWALLPAPER,
                0,
                tempPath,
                SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
        }
    }
}

它在第一次运行时工作正常,但在第二次运行时返回 IOException。显然该文件仍在某处使用。我怎样才能找到它仍在使用的地方?这是异常消息:

System.IO.IOException 未处理
消息=进程无法访问文件“C:\Users\David\documents\visual studio 2010\Projects\Imgur 壁纸\Imgur 壁纸\bin\Debug\Image.bmp”,因为它正在被使用通过另一个过程。
Source=mscorlib
StackTrace:在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) 在 System.IO.File.Delete(String path)

4

2 回答 2

1

我总是发现这个工具非常有助于弄清楚是什么锁定了哪个文件。

我有一段时间没用了,但值得一试。

于 2012-05-11T16:01:14.883 回答
1

完成后,您不会关闭下载流。如果你不这样做,流仍然挂接到文件。尝试使用 .Close() 和 .Dispose()

于 2012-05-11T16:00:08.427 回答