0

我在这个程序中遇到了一个奇怪的错误,它从互联网上下载了一张照片,然后我将它转换为 .jpeg,然后我删除了第一张照片(以 .png 格式)。但我收到一个错误:文件正在被另一个进程使用。为什么会这样?我没有打开文件,也没有人使用它。

string outFile;
outFile = Path.GetTempFileName();
try
{
    webClient.DownloadFile(foto, outFile);
    if (foto.Substring(foto.Length - 3) == "png")
    {
        System.Drawing.Image image1 = System.Drawing.Image.FromFile(outFile);
        foto = foto.Remove(foto.Length - 3) + "jpg";
        string outFile2 = Path.GetTempFileName();
        image1.Save(outFile2, System.Drawing.Imaging.ImageFormat.Jpeg);
        System.IO.File.Delete(outFile);                      
        outFile = outFile2;
    }
}
4

2 回答 2

4

FromFile 保持文件打开,你必须使用这样的东西:

// Load image
FileStream filestream;
filestream = new FileStream("Filename",FileMode.Open, FileAccess.Read);
currentImage = System.Drawing.Image.FromStream(filestream);
filestream.Close();
于 2012-12-11T11:10:01.363 回答
0

system.Drawing.Image 保留文件,只需将 image1 包装在 using 语句中。

        string foto = "http://icons.iconarchive.com/icons/mazenl77/I-like-buttons/64/Style-Config-icon.png";
        string outFile = Path.GetTempFileName(); 
        WebClient webClient = new WebClient();
        try
        {
            webClient.DownloadFile(foto, outFile);
            if (Path.GetExtension(foto).ToUpper() == ".PNG")
            {
                string outFile2 = Path.GetTempFileName();
                using (System.Drawing.Image image1 = System.Drawing.Image.FromFile(outFile))
                {
                    image1.Save(outFile2, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                System.IO.File.Delete(outFile);
            }
        }
于 2012-12-11T11:21:04.587 回答