整理文件操作(四)Image.FromFile(path)

  整理文件操作(一)

  提出了文件是否存在,我的服务器中。

  现在要确定该文件是否为图像文件。

 public static Image TestImageFile(string path)
        {
            
            try
            {
                Image image = Image.FromFile(path);

                return image;
            }
            catch(Exception e)
            {
                throw e;
            }

        }

  我直接使用了Image类中的FromFile方法,这里是微软的介绍

  文档中提出了,该文件没有有效的图像格式,就会返回异常,代码中使用try catch获取异常。

  当然,使用Image类的FromFile方法,还是可以返回文件不存在的异常。

  第一步,我就有必要确认,文件是否存在。这个业务流程是清晰的,接下来只会出现唯一一种异常,就是文件是不是图像文件。

 [TestMethod]
        [ExpectedException(typeof(OutOfMemoryException))]
        public void TestMethod1()
        {

            //布置
            string txtFile = @"E:	estfile01.txt";

            PrivateType po = new PrivateType(typeof(Program));

            //动作
            po.InvokeStatic("TestImageFile", txtFile);
        }

        [TestMethod]    
        public void TestMethod3()
        {
            //布置       
            string pngFile = @"E:IISSub.png";

            PrivateType po = new PrivateType(typeof(Program));

            //动作           
            Image image = po.InvokeStatic("TestImageFile", pngFile) as Image;

            //断言
            Assert.AreEqual(image.RawFormat, ImageFormat.Png);
        }

  这是两个单元测试。确定这段代码是可以验证

  a.确定文件不是图像文件

  b.确定文件是图像文件

  链接:https://pan.baidu.com/s/1ey9rzQtv6OZcWB-UujtlDg
  提取码:baee
  复制这段内容后打开百度网盘手机App,操作更方便哦

原文地址:https://www.cnblogs.com/158-186/p/10939865.html