这个程序出现了一个奇怪的错误,它从互联网上下载了一张照片,然后我将其转换为.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;
}
}
答案 0 :(得分:4)
FromFile保持文件打开,你必须使用这样的东西:
// Load image
FileStream filestream;
filestream = new FileStream("Filename",FileMode.Open, FileAccess.Read);
currentImage = System.Drawing.Image.FromStream(filestream);
filestream.Close();
答案 1 :(得分: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);
}
}