This is a migrated thread and some comments may be shown as answers.

IOException when saving

23 Answers 721 Views
AsyncUpload
This is a migrated thread and some comments may be shown as answers.
John Chatt
Top achievements
Rank 1
John Chatt asked on 07 May 2010, 06:57 PM
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);
    }

23 Answers, 1 is accepted

Sort by
0
Genady Sergeev
Telerik team
answered on 10 May 2010, 03:20 PM
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.
0
Jason Potter
Top achievements
Rank 1
answered on 15 May 2010, 03:06 PM
Hi There,

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

Regards
Jason
0
John Chatt
Top achievements
Rank 1
answered on 17 May 2010, 06:00 PM
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.
0
John Chatt
Top achievements
Rank 1
answered on 17 May 2010, 06:43 PM
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();
0
John Chatt
Top achievements
Rank 1
answered on 17 May 2010, 08:02 PM
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
0
Genady Sergeev
Telerik team
answered on 19 May 2010, 12:27 PM
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.
0
Davide Giavazzoli
Top achievements
Rank 1
answered on 30 Jun 2010, 04:01 PM
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 
0
Genady Sergeev
Telerik team
answered on 02 Jul 2010, 02:10 PM
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
0
Davide Giavazzoli
Top achievements
Rank 1
answered on 02 Jul 2010, 02:33 PM
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
0
Genady Sergeev
Telerik team
answered on 02 Jul 2010, 02:55 PM
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
0
Davide Giavazzoli
Top achievements
Rank 1
answered on 02 Jul 2010, 03:18 PM
Great Genady ! IT WORKS ! Thanx a lot ...
0
mastermehdi
Top achievements
Rank 2
answered on 03 Jul 2010, 11:46 AM

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 ?

0
Genady Sergeev
Telerik team
answered on 05 Jul 2010, 12:29 PM
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
0
Jonx
Top achievements
Rank 2
answered on 27 Jan 2011, 01:25 AM
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.
0
Scott
Top achievements
Rank 1
answered on 18 Jul 2011, 07:53 PM
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
0
Jonx
Top achievements
Rank 2
answered on 18 Jul 2011, 08:19 PM
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.
0
Scott
Top achievements
Rank 1
answered on 19 Jul 2011, 03:25 PM
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
0
Jonx
Top achievements
Rank 2
answered on 19 Jul 2011, 07:40 PM
Good for you :)
John.
0
Peter
Top achievements
Rank 1
answered on 05 Aug 2012, 07:41 PM
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
0
Peter
Top achievements
Rank 1
answered on 07 Aug 2012, 07:20 PM
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 :)
0
Christopher Lee
Top achievements
Rank 1
answered on 09 May 2018, 05:42 PM
Genady, thank you!!!!! This was a huge pain and I could not figure out how to fix until I read your post. Again, much thanks sir!!
0
swapnil
Top achievements
Rank 1
Iron
answered on 01 Feb 2019, 11:54 PM

I do UploadedFile.SaveAs(path) it saves file to disk successfully, this uploadedFile has one property InputStream , this inputstream becomes null as soon as .SaveAs method is completed. i want to use this inputstream after SaveAs method is executed. How i can achieve this ?

public void Upload(UploadedFile file, string entityValue, string path, string domain, string org, string repNum, string entityType)
        {
               file.SaveAs(path); // This save file to local disk successfully

// After above line executes file.inputStrream becomes null and my obj.Upload method fails, how to fix this ?
               
                obj.Upload(file, entityValue, path, domain, org, repNum, entityType);
            

        }

0
Marin Bratanov
Telerik team
answered on 04 Feb 2019, 04:26 PM
Hi Swapnil,

You can find my answer in the other thread you posted this question in: https://www.telerik.com/forums/is-uploadedfile-saveas-asynchronous#qS4fzo5ys06Cb7dWGXeDkQ.


Regards,
Marin Bratanov
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Tags
AsyncUpload
Asked by
John Chatt
Top achievements
Rank 1
Answers by
Genady Sergeev
Telerik team
Jason Potter
Top achievements
Rank 1
John Chatt
Top achievements
Rank 1
Davide Giavazzoli
Top achievements
Rank 1
mastermehdi
Top achievements
Rank 2
Jonx
Top achievements
Rank 2
Scott
Top achievements
Rank 1
Peter
Top achievements
Rank 1
Christopher Lee
Top achievements
Rank 1
swapnil
Top achievements
Rank 1
Iron
Marin Bratanov
Telerik team
Share this question
or