-1

要保存图像,我使用以下代码:

 string filenamewithpath =
      System.Web.HttpContext.Current.Server.MapPath(
           @"~/userimages/" + incID + ".jpg");
 System.IO.File.WriteAllBytes(filenamewithpath, Util.ReadFully(image));


public class Util
    {
        public static byte[] ReadFully(Stream stream)
        {
            byte[] buffer = new byte[32768];
            using (MemoryStream ms = new MemoryStream())
            {
                while (true)
                {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                        return ms.ToArray();
                    ms.Write(buffer, 0, read);
                }
            }
        }
    }

以上适用于使用 ID 保存图像。更新时,我需要覆盖现有图像,并且需要一些有关如何执行此操作的建议。

4

2 回答 2

4

如果您只需要在编写新图像文件之前摆脱旧图像文件,为什么不直接调用

if (System.IO.File.Exists(filenamewithpath)
{
    System.IO.File.Delete(filenamewithpath);
}

虽然, System.IO.File.WriteAllBytes 的描述已经说“如果文件存在,则将其覆盖”。

于 2012-05-03T10:11:07.573 回答
2
System.IO.File.WriteAllBytes(filenamewithpath, Util.ReadFully(image));

将此行替换为:

using (FileStream fs = new FileStream(filenamewithpath, FileMode.OpenOrCreate))
{
    var bytes=Util.ReadFully(image);
    fs.Write(bytes, 0, bytes.Length);
}
于 2012-05-03T10:39:57.573 回答