IOException when saving

21 posts, 0 answers
  1. John Chatt
    John Chatt avatar
    24 posts
    Member since:
    Feb 2010

    Posted 07 May 2010 Link to this post

    When I select a file it is automatically uploaded to the specified temp directory but then when I try to run SaveAs() I get an IOException "The process cannot access the file because it is being used by another process."

    FRONT END:              

     <rad:RadAsyncUpload ID="uplProofFile" runat="server" MaxFileInputsCount="1" Width="500" OnInit="uplProofFile_Init"
                        ControlObjectsVisibility="None" OnFileUploaded="uplProofFile_FileUploaded" TemporaryFileExpiration="02:00:00" >
                    </rad:RadAsyncUpload>

    CODE BEHIND:

        protected void uplProofFile_FileUploaded(object sender, FileUploadedEventArgs e)
        {
                        uplProofFile.UploadedFiles[0].SaveAs(SaveLocation);
        }

  2. Genady Sergeev
    Admin
    Genady Sergeev avatar
    1596 posts

    Posted 10 May 2010 Link to this post

    Hi John Chatt,

    How do you craft the save location propery? Does it contain the full path + the name of the uploaded file? I can't see anything wrong with your code and it should have worked as long as the save location passed to the SaveAs method is correct.

    Sincerely yours,
    Genady Sergeev
    the Telerik team

    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. Jason Potter
    Jason Potter avatar
    10 posts
    Member since:
    Sep 2006

    Posted 15 May 2010 Link to this post

    Hi There,

    Did you get a solution to this as i have a similar problem.

    Regards
    Jason
  5. John Chatt
    John Chatt avatar
    24 posts
    Member since:
    Feb 2010

    Posted 17 May 2010 Link to this post

    The SaveLocation is the full path and file name. since the IOException is "The process cannot access the file because it is being used by another process." It would seem that the path the file is saved to is not the issue but accessing the temp file is the problem.

    Have tried a few different things but nothings works so far.
  6. John Chatt
    John Chatt avatar
    24 posts
    Member since:
    Feb 2010

    Posted 17 May 2010 Link to this post

    Prior to running the SaveAs() function I access   uplProofFile.UploadedFiles[0].InputStream   to generate and MD5 Hash of the file.
    This seems to be what is holding access to the file. If i run SaveAs prior to calling   uplProofFile.UploadedFiles[0].InputStream   The file saves but then I get an error on the   uplProofFile.UploadedFiles[0].InputStream   call.
    Is there a way to get the MD5 Hash of the InputStream and then run SaveAs();
  7. John Chatt
    John Chatt avatar
    24 posts
    Member since:
    Feb 2010

    Posted 17 May 2010 Link to this post

    RESOLVED:

    needed to

                    var streamForMD5 = uplProofFile.UploadedFiles[0].InputStream;
                    md5Hash = Utility.GenerateMD5(streamForMD5);
                    streamForMD5.Dispose();
                    uplProofFile.UploadedFiles[0].SaveAs(newFile);

    this worked

    hope that helps
  8. Genady Sergeev
    Admin
    Genady Sergeev avatar
    1596 posts

    Posted 19 May 2010 Link to this post

    Hello John Chatt,

    Alternatively you can use the using keyword. Whenever streams are used  it is a very good idea to use using since it will release the stream for you. Example code:

    using(Stream stream = uplProofFile.UploadedFiles[0].InputStream)
    {
        md5Hash = Utility.generateMD5(stream);
    }
      
    uplProofFile.UploadedFiles[0].SaveAs(newFile);



    Best wishes,
    Genady Sergeev
    the Telerik team

    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
  9. Davide Giavazzoli
    Davide Giavazzoli avatar
    3 posts
    Member since:
    May 2010

    Posted 30 Jun 2010 Link to this post

    Hi, I have a very similar problem and i need some help ...
    I use a custom control with a thumbnail and a asyncupload control
    when i upload a file the thumbnail show the image (that's ok)
    then I commit a postback to save that temp file and i get the error about concurrent access to the temp file
    I tried to dispose everything but ... nothing ... Any idea ?

    Custom control
    <%@ Control Language="VB" AutoEventWireup="false" CodeFile="imageUpload.ascx.vb" Inherits="Controls_imageUpload" %> 
     
     
     
       <telerik:RadAjaxManagerProxy ID="RadAjaxManagerProxy1" runat="server">  
            <AjaxSettings> 
                <telerik:AjaxSetting AjaxControlID="RadAjaxManagerProxy1">  
                    <UpdatedControls> 
                        <telerik:AjaxUpdatedControl ControlID="Thumbnail" /> 
                    </UpdatedControls> 
                </telerik:AjaxSetting> 
            </AjaxSettings> 
       </telerik:RadAjaxManagerProxy> 
     
        <script type="text/javascript">  
            function fileUploaded(sender, args) {  
                $find('ctl00_RadAjaxManger1').ajaxRequest();  
                //sender.deleteFileInputAt(0);  
            }   
        </script> 
     
     
     
          
            <%-- For the purpose of this demo the files are discarded.  
                 In order to store the uploaded files permanently set the TargetFolder property to a valid location. --%> 
            <telerik:RadBinaryImage runat="server" Width="200px" Height="150px" ResizeMode="Fit" ID="Thumbnail" ImageUrl="~/App_Themes/Adminarea/images/blankimage.png" /> 
              
            <telerik:RadAsyncUpload runat="server" ID="AsyncUpload1" MaxFileInputsCount="1" OnClientFileUploaded="fileUploaded" OnFileUploaded="AsyncUpload1_FileUploaded" TemporaryFolder="~/Upload" > 
               <Localization Select="Scegli" /> 
            </telerik:RadAsyncUpload> 

    Code Behind Custom control
        Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load  
            AsyncUpload1.TargetPhysicalFolder = Server.MapPath("~/Upload/images")  
        End Sub  
        Protected Sub AsyncUpload1_FileUploaded(ByVal sender As Object, ByVal e As FileUploadedEventArgs)  
            Thumbnail.Width = Unit.Pixel(200)  
            Thumbnail.Height = Unit.Pixel(150)  
     
            Dim imageData As Byte() = New Byte(e.File.InputStream.Length) {}  
            e.File.InputStream.Read(imageData, 0, e.File.InputStream.Length)  
            Thumbnail.DataValue = imageData 
     
        End Sub 

    Code executed after postback i a page containing the custom control above
                    Dim Auc As RadAsyncUpload  
                    Auc = CType(radMultiPage1.FindControl(dr("sPH")).FindControl(dr("sNomeControllo").ToString & lang).FindControl("AsyncUpload1"), RadAsyncUpload)  
                      
                    If Auc.UploadedFiles.Count > 0 Then  
     
                        value = Auc.UploadedFiles(0).FileName  
                        Auc.UploadedFiles(0).SaveAs(Server.MapPath("~/Upload/images/") & value)  
                    Else  
                        value = "NULL" 
                    End If 
  10. Genady Sergeev
    Admin
    Genady Sergeev avatar
    1596 posts

    Posted 02 Jul 2010 Link to this post

    Hi Davide Giavazzoli,

    Please invoke the close method of e.File.InputStream after having finished working with him. Translated into code this would work like this:

    Thumbnail.Width = Unit.Pixel(200) 
    Thumbnail.Height = Unit.Pixel(150) 
      
    Dim imageData As Byte() = New Byte(e.File.InputStream.Length) {} 
    e.File.InputStream.Read(imageData, 0, e.File.InputStream.Length) 
    Thumbnail.DataValue = imageData
    e.File.InputStream.Close()

    Does the issue persist?

    All the best,
    Genady Sergeev
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  11. Davide Giavazzoli
    Davide Giavazzoli avatar
    3 posts
    Member since:
    May 2010

    Posted 02 Jul 2010 Link to this post

    Sorry, but the problem persists (I tried before also with dispose method without any result);
    "Il processo non può accedere al file perché è in uso da un altro processo". means "The process cannot access the file because it is being used by another process" ... Maybe adding dinamically the control inside another custom control let the process hung ?
    I'm just trying to load a file and have a preview before doing the postback and save that file and other infos. May I try with some complete example ? Have you got any with save method executed ?
    Thanx

    Errore server nell'applicazione '/_mod'.

    Il processo non può accedere al file perché è in uso da un altro processo.

    Descrizione: Eccezione non gestita durante l'esecuzione della richiesta Web corrente. Per ulteriori informazioni sull'errore e sul suo punto di origine nel codice, vedere l'analisi dello stack.

    Dettagli eccezione: System.IO.IOException: Il processo non può accedere al file perché è in uso da un altro processo.

    Errore nel codice sorgente:

    Riga 96: 
    Riga 97:                     value = Auc.UploadedFiles(0).FileName
    Riga 98: Auc.UploadedFiles(0).SaveAs(Server.MapPath("~/Upload/images/") & value)Riga 99:                 Else
    Riga 100:                    value = "NULL"

    File di origine: L:\Modula\_modula\Adminarea\editCard.aspx.vb    Riga: 98

    Analisi dello stack:

    [IOException: Il processo non può accedere al file perché è in uso da un altro processo.]
       System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +7712546
       System.IO.__Error.WinIOError() +33
       System.IO.File.Move(String sourceFileName, String destFileName) +257
       Telerik.Web.UI.AsyncUploadedFile.SaveAs(String fileName, Boolean overwrite) +50
       Telerik.Web.UI.UploadedFile.SaveAs(String fileName) +9
       Modules_cards_editCard.readCellControl(DataRow& dr, String lang) in L:\Modula\_modula\Adminarea\editCard.aspx.vb:98
       Modules_cards_editCard.readTablesOfControls(SqlCommand& objCom) in L:\Modula\_modula\Adminarea\editCard.aspx.vb:228
       Modules_cards_editCard.insertData() in L:\Modula\_modula\Adminarea\editCard.aspx.vb:181
       ASP.adminarea_editcard_aspx._Lambda$__2(Object a0, EventArgs a1) in L:\Modula\_modula\Adminarea\editCard.aspx:24
       System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
       System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
       System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
       System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
       System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565
    
  12. Genady Sergeev
    Admin
    Genady Sergeev avatar
    1596 posts

    Posted 02 Jul 2010 Link to this post

    Hello Davide Giavazzoli,

    Please excuse me, my bad. Here is the correct code that you need to use:

    Thumbnail.Width = Unit.Pixel(200)
    Thumbnail.Height = Unit.Pixel(150)
     
    Dim fileStream As Stream = e.File.InputStream
    Dim imageData As Byte() = New Byte(fileStream.Length - 1) {}
    fileStream.Read(imageData, 0, CInt(fileStream.Length))
    Thumbnail.DataValue = imageData
    fileStream.Close()

    The problem here is that e.File.InputStream always return new instance of the stream to the file, therefore
    e.File.InputStream.Close does not invoke close on any previously used instances but only the current one.

    Greetings,
    Genady Sergeev
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  13. Davide Giavazzoli
    Davide Giavazzoli avatar
    3 posts
    Member since:
    May 2010

    Posted 02 Jul 2010 Link to this post

    Great Genady ! IT WORKS ! Thanx a lot ...
  14. mastermehdi
    mastermehdi avatar
    39 posts
    Member since:
    Apr 2010

    Posted 03 Jul 2010 Link to this post

    Hi, I have a very similar problem too and i need some help ...

    FRONT END:
    <telerik:RadAsyncUpload ID="radAsyncUpload" runat="server" />
    <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="upload" />

    CODE BEHIND:

    protected void btnUpload_Click(object sender, EventArgs e)

    {

        bool valid = false;

        using(System.Drawing.Image image = System.Drawing.Image.FromStream(radAsyncUpload.UploadedFiles[0].InputStream))

        {

    if (image.Width >= 1024 && image.Height >= 768)

            {

                valid = true;

            }

        }

        if (valid)

        {

            radAsyncUpload.UploadedFiles[0].SaveAs(MapPath("~/banners") + radAsyncUpload.UploadedFiles[0].FileName, true);

        }

    }

    but when I try to run SaveAs() I get an IOException "The process cannot access the file because it is being used by another process."

    I tried to dispose everything but ... nothing ... Any idea ?

  15. Genady Sergeev
    Admin
    Genady Sergeev avatar
    1596 posts

    Posted 05 Jul 2010 Link to this post

    Hello mehdi ghasemi,

    The problem that you face is the same. You need to obtain only a single reference pointing to the uploaded file stream and close it after having finished working with it. This how your code should look like:

    bool valid = false;
            using (Stream fileStream = RadAsyncUpload1.UploadedFiles[0].InputStream)
            {
                using (System.Drawing.Image image = System.Drawing.Image.FromStream(fileStream))
                {
                    if (image.Width >= 1024 && image.Height >= 768)
                    {
                        valid = true;
                    }
                }
            }
     
            if (valid)
            {
                RadAsyncUpload1.UploadedFiles[0].SaveAs(MapPath("~/banners") + RadAsyncUpload1.UploadedFiles[0].FileName, true);
            }


    Sincerely yours,
    Genady Sergeev
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  16. Jonx
    Jonx avatar
    258 posts
    Member since:
    Jul 2012

    Posted 26 Jan 2011 Link to this post

    Just for the record, I had the same exception when saving the file and using the following code:
    protected void onModeleUploaded(object sender, FileUploadedEventArgs e)
            {
                if (uplModele.UploadedFiles.Count > 0)
                {
                    foreach (UploadedFile f in uplModele.UploadedFiles)
                    {
                        string file = f.GetName();
                         
                        f.SaveAs(file, true);
                    }
                }
            }

    The problem with that code is that you read and write to the same file. You need to save your file to another location for that code to work.
    Like that for exemple:
    string file = Path.Combine(MapPath("~/App_Data/Template/"), f.GetName());
    f.SaveAs(file, true);

    John.
  17. Scott
    Scott avatar
    4 posts
    Member since:
    Jan 2011

    Posted 18 Jul 2011 Link to this post

    Hi,
       I am Having same problem too .

    UploadedFileCollection files = RadAsyncUpload1.UploadedFiles;
    if (files.Count > 0)
                      {
                          foreach (UploadedFile file in files)
                          {
                            try
                              {
                                  string ext = System.IO.Path.GetExtension(file.FileName).ToLower();
                               
                                  if (ext != ".exe" && ext != ".vbs" && ext != ".bat" && ext != ".gif" && ext != ".jpeg" && ext != ".bmp")
                                  {
     
                                 
                                      string currentFilename = System.IO.Path.GetFileName(file.FileName);
                                      string newFilename = DateTime.Now.Ticks.ToString() + ext;
                                      string filepath = Server.MapPath("..\\uploads\\store") + "\\" + newFilename;
                                          BinaryReader br = new BinaryReader(file.InputStream);
                                      byte[] FileData = br.ReadBytes((int)file.ContentLength);
                                      br.Close();
                                      file.SaveAs(filepath);  // Error File is used by another process ??
     
             }
    }
    }}

    Am I doing anything Wrong or missing something ?
    Thanks
    Nirav
  18. Jonx
    Jonx avatar
    258 posts
    Member since:
    Jul 2012

    Posted 18 Jul 2011 Link to this post

    Why do you need this ? Maybe this does not close fast enought... Just remove the 3 lines... (maybe I missed something?)
    BinaryReader br = new BinaryReader(file.InputStream);
    byte[] FileData = br.ReadBytes((int)file.ContentLength);
    br.Close();

    Just build your filename and write to it...
    The rest is done for you...

    John.
  19. Scott
    Scott avatar
    4 posts
    Member since:
    Jan 2011

    Posted 19 Jul 2011 Link to this post

    Hi John
                never mind I figured it out .
    Below Is code what I was trying to achieve

      
    string currentFilename = System.IO.Path.GetFileName(file.FileName);
                                      string newFilename = DateTime.Now.Ticks.ToString() + ext;
                                      string filepath = Server.MapPath("..\\uploads\\store") + "\\" + newFilename;
                                     
                                      
                                      file.SaveAs(filepath);
                                      string pdfpath = String.Empty;
                                      //pdf conversion of document
                                      switch (ext)
                                      {
                                          case ".pdf":
                                              pdfpath = filepath;
                                              break;
                                          case ".doc":
                                              pdfpath = StreamLink.PrintGen.ConvertDOC(filepath, ".doc");
                                              break;
                                          case ".txt":
                                              pdfpath = StreamLink.PrintGen.ConvertDOC(filepath, ".txt");
                                              break;
                                          case ".docx":
                                              pdfpath = StreamLink.PrintGen.ConvertDOC(filepath, ".docx");
                                              break;
                                          case ".xls":
                                              pdfpath = StreamLink.PrintGen.ConvertDOC(filepath, ".xls");
                                              break;
                                          case ".xlsx":
                                              pdfpath = StreamLink.PrintGen.ConvertDOC(filepath, ".xlsx");
                                              break;
                                          case ".ppt":
                                              pdfpath = StreamLink.PrintGen.ConvertDOC(filepath, ".ppt");
                                              break;
                                          case ".pptx":
                                              pdfpath = StreamLink.PrintGen.ConvertDOC(filepath, ".pptx");
                                              break;
                                          case ".dot":
                                              StreamLink.PrintGen.ConvertDOC(filepath, ".docx");
                                              break;
                                          case ".xlt":
                                              pdfpath = StreamLink.PrintGen.ConvertDOC(filepath, ".xlsx");
                                              break;
                                          default:
     
                                              break;
                                      }
                                      using (SqlConnection connection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString1"]))
                                      {
                                          connection.Open();
                                          //Get meeting folder
                                          //  int FolderID = GetMeetingFolder(Int32.Parse(OrgID), Int32.Parse(MeetingID));
     
                                          //Add file record and get id
     
                                          SqlCommand cmd = new SqlCommand("BoardSource_InsertFile", connection);
                                          FileStream filestream = new FileStream(filepath, FileMode.Open, FileAccess.Read);
                                          BinaryReader br = new BinaryReader(filestream);
                                          byte[] FileData = br.ReadBytes((int)file.ContentLength);
                                          br.Close();
                                          cmd.CommandType = CommandType.StoredProcedure;
     
     
                                          cmd.Parameters.Add(new SqlParameter("@Filename", currentFilename));
                                          cmd.Parameters.Add(new SqlParameter("@FilePath", filepath));
                                          cmd.Parameters.Add(new SqlParameter("@FileType", ext.Trim('.')));
                                          cmd.Parameters.Add(new SqlParameter("@OrgID", 18));
                                          cmd.Parameters.Add(new SqlParameter("@ParentFolder", 0));
                                          cmd.Parameters.Add(new SqlParameter("@FileData", FileData));
     
     
                                          SqlParameter FileIDParameter = new SqlParameter("@FileID", SqlDbType.Int);
                                          FileIDParameter.Direction = ParameterDirection.Output;
                                          cmd.Parameters.Add(FileIDParameter);
     
     
                                          cmd.ExecuteNonQuery();

    thanks
    Nirav
  20. Jonx
    Jonx avatar
    258 posts
    Member since:
    Jul 2012

    Posted 19 Jul 2011 Link to this post

    Good for you :)
    John.
  21. Peter
    Peter avatar
    6 posts
    Member since:
    Jun 2012

    Posted 05 Aug 2012 Link to this post

    Same issue here. Not sure why it's giving me the error.

    protected void RadAsyncUpload1_FileUploaded(object sender, FileUploadedEventArgs e) {
     
        ListViewItem lvwItem = lvwItems.EditItem;
        RadAsyncUpload upl = (RadAsyncUpload)lvwItem.FindControl("RadAsyncUpload1");
     
        string target = MapPath(upl.TargetFolder);
        foreach (UploadedFile file in upl.UploadedFiles) {
     
            using (Bitmap originalImage = new Bitmap(file.InputStream)) {
                System.Drawing.Image cloneImage = (Bitmap)originalImage.Clone();
                 
                // Resize the picture to max 200 * 200
                Size mySize = new Size(200, 200);
                cloneImage = Imaging.resizeImage(originalImage, mySize);
                Bitmap newImage = new Bitmap(cloneImage);
     
                // Convert to jpg if necessary
                if (file.GetExtension() != ".jpeg" || file.GetExtension() != ".jpg") {
                    Imaging.saveJpeg(Path.Combine(target, file.GetNameWithoutExtension() + ".jpg"), newImage, 100);
                }
     
                mySize.Height = 50;
                mySize.Width = 50;
                cloneImage = Imaging.resizeImage(originalImage, mySize);
                Imaging.saveJpeg(Path.Combine(target, file.GetNameWithoutExtension() + "_lille.jpg"), newImage, 100);
     
                uploadedFileName = Path.Combine(target, file.GetNameWithoutExtension() + ".jpg");
            }
        }
    }

    I tried cloising and disposing the file.inputstream, but no go.

    Anyone got any ideas?

    Thanks :)

    Peter
  22. Peter
    Peter avatar
    6 posts
    Member since:
    Jun 2012

    Posted 07 Aug 2012 Link to this post

    My error was caused by the line:

    using (Bitmap originalImage = new Bitmap(file.InputStream))

    I replaced that with:

    using (Stream fileStream = file.InputStream) {
                            using (System.Drawing.Image originalImage = System.Drawing.Image.FromStream(fileStream)) {

    Problem solved :)
Back to Top
UI for ASP.NET Ajax is Ready for VS 2017