#

Asp.Net IOException: The process cannot access the file xx because it is being used by another process.

 

Fehler:

wenn man ein Foto zwei mal auf einen Asp.Net Webserver hochlädt, dann entsteht beim zweiten Mal eine Fehlermeldung, dass die Datei welche man hochlädt gesperrt sei durch einen anderen Prozess.

 

Fehlermeldung

Im Browser beim zweiten Hochladen

An unhandled exception occurred while processing the request.

IOException: The process cannot access the file 'C:\_Daten\Desktop\xxx\wwwroot\User_Files\User_Images\Original\User_Image_1.jpg' because it is being used by another process.

System.IO.FileStream.OpenHandle(FileMode mode, FileShare share, FileOptions options)

 

Fehler-Details
Die fehlerhafte Detailzeile zeigt auf Using var Stream = new Filestream

76.              //< Copy File to Target >

82.              using (var stream = new FileStream(sFile_Target_Original, FileMode.Create))

83.              {

84.                  await uploaded_File.CopyToAsync(stream);

85.              }

86.              //</ Copy File to Target >

87.   

88.                //< resize

 

Fehleranzeige

 

Lösung:

Beim Hochladen einer Datei in Asp.Net Core MVC und einer anschliessenden Nachbearbeitung wie Zoom, Size oder Crop wird im Windows Core Bildbearbeitungsprozess die Bearbeitungsdatei geöffnet aber am Ende nicht geschlossen.

 

Die Fehlerhafte Zeile ist

Bitmap source_Bitmap = new Bitmap(System.Drawing.Image.FromFile(input_Image_Path));  //Error:

 

Der Fehler wird durch die System.Drawing.Image.FromFile(..) verursacht.

Dabei wird für die Übergabe ein Image-Objekt erstellt und dieses an die Bitmap übergeben. Nach den Arbeiten bleibt aber das Image geöffnet.

 

Lösung:

Man kann direkt ein Bitmap aus einem Filepath erstellen:

Bitmap source_Bitmap = new Bitmap(input_Image_Path);

 

 

 

Beispiel wo der Fehler auftritt:

Wenn ein Foto hochgeladen, auf dem Web Server  gespeichert wird und anschliessend in der Größe angepasst wird, dann bleibt im Image-Bearbeitungs Code das Original-Image geöffnet.

Deshalb entsteht der Schreib-Fehler

 

Code Beispiel:  Asp.Net Mvc Core 2

 

Foto-Uploader mit Größen-Anpassung

Mit korrektem Code

 

 

Upload Image Controller

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using System.IO;                    //*Directory copy Files

using Microsoft.AspNetCore.Http;    //*IFormFile

using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Hosting; //*get RootPath

using System.Drawing;               //CoreCompat Image handling

using System.Drawing.Drawing2D;     //CoreCompat Image handling

using System.Drawing.Imaging;       //CoreCompat Image handling

using IWois_Core.Data;              //ApplicationDbContext Database connection

using Microsoft.AspNetCore.Authorization;   //Identity: Register,Login

using Microsoft.AspNetCore.Authentication;  //Identity: Register,Login

using Microsoft.AspNetCore.Identity;        //Identity: Register,Login

 

namespace IWois_Core.Controllers

{

    public class ImageController : Controller

    {

        private readonly ApplicationDbContext _context;

        private readonly IHostingEnvironment _appEnvironment;

       

        public ImageController(ApplicationDbContext context, IHostingEnvironment appEnvironment)

        {

            //----< Init: Controller >----

            _context = context;

            _appEnvironment = appEnvironment;           

            //----</ Init: Controller >----

        }

 

 

        [Authorize]

        [HttpGet] //1.Load

        public IActionResult Upload_User_Profil_Image()

        {

            //--< Upload Form >--

            return View();

            //--</ Upload Form >--

        }

 

        [Authorize]

        [HttpPost] //Postback

        public async Task<IActionResult> Upload_User_Profil_Image(IFormFile uploaded_File)

        {

            //--------< Upload_ImageFile() >--------

            string sResult = "";

 

 

            //< check >

            if (uploaded_File == null || uploaded_File.Length == 0)

            {

                ViewData["Error"] = "Error:file not selected";

                return View(ViewData);

            }

 

            if (uploaded_File.ContentType.IndexOf("image", StringComparison.OrdinalIgnoreCase) < 0)

            {

                ViewData["Error"] = "Error:This file is not an image";

                return View(ViewData);

            }

            //</ check >

 

            //--< Get User ID >--

            //internal referenz-Number for tracking in tables

            long IDUser = await Common.ExtensionMethods.getIDUser_Number(this.User, _context);

            //--</ Get User ID >--

 

            //< init >

            string sImage_Folder = "User_Images";

            string sTarget_Filename = "User_Image_" + IDUser + ".jpg";

            //</ init >

 

            //< get Path >

            string sPath_WebRoot = _appEnvironment.WebRootPath;

            string sPath_of_Target_Folder = sPath_WebRoot + "\\User_Files\\" + sImage_Folder + "\\";

            string sFile_Target_Original = sPath_of_Target_Folder + "\\Original\\" + sTarget_Filename;

            //string sImage_Filename_Original = sPath_of_Target_Folder + uploaded_File.FileName;

            //</ get Path >

 

            //< Copy File to Target >

            using (var stream = new FileStream(sFile_Target_Original, FileMode.Create))

            {

                await uploaded_File.CopyToAsync(stream);

            }

            //</ Copy File to Target >

 

            //< resize >

            Image_resize(sFile_Target_Original, sPath_of_Target_Folder + "\\40\\" + sTarget_Filename, 40);

            Image_resize(sFile_Target_Original, sPath_of_Target_Folder + "\\80\\" + sTarget_Filename, 80);

            Image_resize(sFile_Target_Original, sPath_of_Target_Folder + "\\120\\" + sTarget_Filename, 120);

            Image_resize(sFile_Target_Original, sPath_of_Target_Folder + "\\240\\" + sTarget_Filename, 240);

            Image_resize(sFile_Target_Original, sPath_of_Target_Folder + "\\400\\" + sTarget_Filename, 400);

            //</ resize >

 

            //string sResult= await Safe_Uploaded_Image(ref uploaded_File, "User_Images");

 

 

            //< output >

            ViewData["FileUploaded"] = "/User_Files/User_Images/Original/" + sTarget_Filename;

            return View();

            //</ output >

            //--------</ Upload_ImageFile() >--------

        }

 

 

        private void Image_resize(string input_Image_Path, string output_Image_Path,int new_Width)

        {

            //---------------< Image_resize() >---------------

            //*Resizes an Image in Asp.Net MVC Core 2

            //*Using Nuget CoreCompat.System.Drawing

            //using System.IO

            //using System.Drawing;             //CoreCompat

            //using System.Drawing.Drawing2D;   //CoreCompat

            //using System.Drawing.Imaging;     //CoreCompat

 

            const long quality = 50L;

            Bitmap source_Bitmap = new Bitmap(input_Image_Path);

            //Bitmap source_Bitmap = new Bitmap(System.Drawing.Image.FromFile(input_Image_Path));  //Error:

 

            double dblWidth_origial = source_Bitmap.Width;

            double dblHeigth_origial = source_Bitmap.Height;

            double relation_heigth_width = dblHeigth_origial / dblWidth_origial;

            int new_Height = (int)(new_Width * relation_heigth_width);

 

            //< create Empty Drawarea >

            var new_DrawArea = new Bitmap(new_Width, new_Height);

            //</ create Empty Drawarea >

 

            using (var graphic_of_DrawArea = Graphics.FromImage(new_DrawArea))

            {

                //< setup >

                graphic_of_DrawArea.CompositingQuality = CompositingQuality.HighSpeed;

                graphic_of_DrawArea.InterpolationMode = InterpolationMode.HighQualityBicubic;

                graphic_of_DrawArea.CompositingMode = CompositingMode.SourceCopy;

                //</ setup >

 

                //< draw into placeholder >

                //*imports the image into the drawarea

                graphic_of_DrawArea.DrawImage(source_Bitmap, 0, 0, new_Width, new_Height);

                //</ draw into placeholder >

 

                //--< Output as .Jpg >--

                using (var output = System.IO.File.Open(output_Image_Path, FileMode.Create))

                {

                    //< setup jpg >

                    var qualityParamId = Encoder.Quality;

                    var encoderParameters = new EncoderParameters(1);

                    encoderParameters.Param[0] = new EncoderParameter(qualityParamId, quality);

                    //</ setup jpg >

 

                    //< save Bitmap as Jpg >

                    var codec = ImageCodecInfo.GetImageDecoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);

                    new_DrawArea.Save(output, codec, encoderParameters);

                    //resized_Bitmap.Dispose();

                    output.Close();

                    //</ save Bitmap as Jpg >

                }

                //--</ Output as .Jpg >--

                graphic_of_DrawArea.Dispose();

            }

            source_Bitmap.Dispose();

            //---------------</ Image_resize() >---------------

        }

 

    }

}

 

 

 

 

 

View Code asp.net mvc core

@{

    Layout = null;

}

 

<!DOCTYPE html>

 

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Upload_Image</title>

</head>

<body>

    <br /><br />

    <span style="margin-top:10px;"> Upload Your Profil Image:</span>

    <br />

    <form asp-controller="Image" asp-action="Upload_User_Profil_Image" method="post"

          enctype="multipart/form-data">

 

        <input type="file" name="uploaded_File" />

        <br />

        <button type="submit" style="">Upload</button>

    </form>

 

    <br />

    <br />

    @if (ViewData["FileUploaded"]!=null)

    {

    <img src="@ViewData["FileUploaded"]" alt="Uploaded Image" />

    }

 

    @if (ViewData["Error"]!=null)

    {

    <label>Error= @ViewData["Error"]</label>

    }

 

    <br />

</body>

</html>

 

 

Mobile

.

0123movie.net