Stream"文件在另一个程序中打开"

时间:2016-07-21 15:19:53

标签: c# stream

我在这段代码中找不到任何错误 每张支票都给了我这个错误"文件在另一个程序中打开" 我认为有一些我无法处置的流

public static void CheckResolution(string imagePath)
{                
    var image = LoadSigleImageFromFile(imagePath);
    var baseArea = 2600 * 1000;//dimenzioni in risoluzione 
    FileStream stream = new FileStream(image.FileInfo.FullName, FileMode.Open, FileAccess.ReadWrite);
    try
    {
        Image img = Image.FromStream(stream);

        var imageArea = img.Height * img.Width;
        if (imageArea >= baseArea)
        {
            var scaleFactor = (imageArea / baseArea);
            var newVerticalRes = (int)(img.Height / scaleFactor);
            var newHorizontalRes = (int)(img.Width / scaleFactor);
            var newImage = ResizeImage(img, new Size(newHorizontalRes, newVerticalRes));

            if (File.Exists(imagePath))
                File.Delete(imagePath);
            newImage.Save(imagePath, ImageFormat.Jpeg);
        }
    }
    catch (Exception ex)
    {
        logger.Error("errore scala foto : " + ex.Message);
        //if (Boolean.Parse(ConfigurationManager.AppSettings["StopOnException"]))
        throw new Exception("CheckResolution errore scala foto : " + ex.Message);
    }
    finally
    {
        stream.Dispose();
    }
}

这里是loadSingle ...功能

public static ImageFromFile LoadSigleImageFromFile(string file)
{
    var ris = new ImageFromFile();
    FileInfo fileInfo = new FileInfo(file);
    if (fileInfo.Name != "Thumbs.db")
        ris = (new ImageFromFile() { FileInfo = fileInfo });

    return ris;
}

更新ResizeImage功能

 private static Image ResizeImage(Image imgToResize, Size size)
    {
        int sourceWidth = (int)imgToResize.Width;
        int sourceHeight = (int)imgToResize.Height;

        float nPercent = 0;
        float nPercentW = 0;
        float nPercentH = 0;

        nPercentW = ((float)size.Width / (float)sourceWidth);
        nPercentH = ((float)size.Height / (float)sourceHeight);

        if (nPercentH < nPercentW)
            nPercent = nPercentH;
        else
            nPercent = nPercentW;

        int destWidth = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);

        Bitmap b = new Bitmap(destWidth, destHeight);
        b.SetResolution(imgToResize.HorizontalResolution, imgToResize.VerticalResolution);
        Graphics g = Graphics.FromImage((System.Drawing.Image)b);
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;

        g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
        g.Dispose();

        return (Image)b;
    }

1 个答案:

答案 0 :(得分:1)

在您的代码中显而易见的是这一行

if (File.Exists(imagePath))
    File.Delete(imagePath);

尝试删除上面Stream打开的同一文件。您应该尝试在关闭之前打开的流之后尝试删除文件(以及以下保存)。

我可以建议这些改变

public static void CheckResolution(string imagePath)
{      
    // Flag becomes true if the resize operation completes
    bool resizeCompleted = false;
    Image newImage = null;          

    // If file doesn't exist the code below returns null.
    var image = LoadSigleImageFromFile(imagePath);
    if(image == null) return;

    var baseArea = 2600 * 1000;//dimenzioni in risoluzione 
    using(FileStream stream = new FileStream(image.FileInfo.FullName, FileMode.Open, FileAccess.ReadWrite))
    {
        try
        {
            Image img = Image.FromStream(stream);
            var imageArea = img.Height * img.Width;
            if (imageArea >= baseArea)
            {
                ... resize ops ....
                // if (File.Exists(imagePath))
                      //File.Delete(imagePath);
                // newImage.Save(imagePath, ImageFormat.Jpeg);

                // Set the flag to true if resize completes
                resizeCompleted = true;
           }
        }
        catch (Exception ex)
        {
            logger.Error("errore scala foto : " + ex.Message);
            throw new Exception("CheckResolution errore scala foto : " + ex.Message);
        }
    }

    // Now you can delete and save....
    if(resizeCompleted)
    {
        // No need to check for existance. File.Delete doesn't throw if
        // the file doesn't exist
        File.Delete(imagePath);
        newImage.Save(imagePath, ImageFormat.Jpeg);
    }
}

public static ImageFromFile LoadSigleImageFromFile(string file)
{
    // Check if the file exists otherwise return null....
    var ris = null;
    if(File.Exists(file))
    {
        FileInfo fileInfo = new FileInfo(file);
        if (fileInfo.Name != "Thumbs.db")
           ris = (new ImageFromFile() { FileInfo = fileInfo });
    }
    return ris;
}

在使用块的右括号之后移动删除和保存操作,您可以确定该文件不再被您自己的程序锁定,您可以继续删除并保存操作

另请注意,在输入此代码之前,您应该检查输入文件是否存在,否则会有例外情况等待您。