如何使用 c# 覆盖现有映像

本文关键字:映像 覆盖 何使用 | 更新日期: 2023-09-27 18:33:06

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

 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 保存图像。更新时,我需要覆盖现有图像,并且需要有关如何执行此操作的一些建议。

如何使用 c# 覆盖现有映像

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

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

虽然,System.IO.File.WriteAllBytes的描述已经说"如果文件存在,它就会被覆盖"。

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);
}