我在路径中编辑pic文件并为其创建新的图像文件。我的代码是:
string[] files = Directory.GetFiles(string.Concat(Server.MapPath("/"), "tmp/"));
foreach (string path in files)
{
string filename = Path.GetFileName(path);
using (Bitmap b = new Bitmap(string.Concat(Server.MapPath("/"), "tmp/", filename)))
{
SolidBrush pixelBrush = new SolidBrush(Color.White);
Graphics g = Graphics.FromImage(b);
g.FillRectangle(Brushes.White, 0, 0, 105, 40);
string outputFileName = string.Concat(Server.MapPath("/"), "tmp\\E", filename);
MemoryStream memory = new MemoryStream();
FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite);
b.Save(memory, ImageFormat.Jpeg);
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
fs.Close();
memory.Close();
b.Dispose();
}
File.Delete(path);
}
删除旧文件时发生的错误是:
其他信息:进程无法访问该文件 'G:\ project \ WebApplication1 \ WebApplication1 \ tmp \ b381ae6.jpg'因为 它被另一个进程使用。
如何解决?
答案 0 :(得分:1)
使用使用包装图形将修复它。你也应该处理它。
using (Bitmap b = new Bitmap(filePath))
{
using (Graphics g = Graphics.FromImage(b))
{
...
}
}
您也可以通过组合使用using语句。
foreach (var path in files)
{
var filename = Path.GetFileName(path);
var filePath = string.Concat(tmpPath, filename);
using (var b = new Bitmap(filePath))
using (var g = Graphics.FromImage(b))
{
g.FillRectangle(Brushes.White, 0, 0, 105, 40);
var outputFileName = string.Concat(newPath, filename);
using (var memory = new MemoryStream())
using (var fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
{
b.Save(memory, ImageFormat.Jpeg);
var bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
File.Delete(path);
}
答案 1 :(得分:0)
使用范围编写代码并检查文件存在
using (var b = new Bitmap(filePath))
using (var g = Graphics.FromImage(b))
using (var memory = new MemoryStream())
using (var fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
bool exists = File.Exists("Path");
if(exists)
{
// Code Here
}
答案 2 :(得分:-1)
在对该文件执行其他操作之前,您需要关闭文件流;)