473,748 Members | 2,276 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problems storing upload file in session (ObjectDisposed Exception)

Hi

I have the following code. I upload an XML file using the FileUpload object,
store the stream in a session so the user gets the chance to confirm some
options then pass the stream from the Session to an XmlReader.

if (performImport == false)
{
Session["__xmlImportFil e"] = fileUpload1.Fil eContent;
//... some other code
}
else
{
if (Session["__xmlImportFil e"] != null)
{
Stream xmlFile = (Stream)Session["__xmlImportFil e"];
xmlFile.Positio n = 0;
// ... pass xmlFile to XmlReader
}
Session.Remove( "__xmlImportFil e");
}

This works fine on the Visual Studio web server. When I transfer the code to
an IIS web server I can only get the code to work if the uploaded file is
80Kb or less. Anything over that and I get an ObjectDisposedE xception
(Cannot access a closed file.) The size in bytes of the stream from the
session appears to be correct before the XmlReader is called.

[ObjectDisposedE xception: Cannot access a closed file.]
System.IO.__Err or.FileNotOpen( ) +56
System.IO.FileS tream.Seek(Int6 4 offset, SeekOrigin origin) +1945963
System.Web.Temp File.GetBytes(I nt32 offset, Int32 length, Byte[] buffer,
Int32 bufferOffset) +35
System.Web.Http RawUploadedCont ent.CopyBytes(I nt32 offset, Byte[] buffer,
Int32 bufferOffset, Int32 length) +112
System.Web.Http InputStream.Rea d(Byte[] buffer, Int32 offset, Int32 count)
+47
System.Xml.XmlT extReaderImpl.I nitStreamInput( Uri baseUri, String
baseUriStr, Stream stream, Byte[] bytes, Int32 byteCount, Encoding encoding)
+196
System.Xml.XmlT extReaderImpl.. ctor(Stream stream, Byte[] bytes, Int32
byteCount, XmlReaderSettin gs settings, Uri baseUri, String baseUriStr,
XmlParserContex t context, Boolean closeInput) +62
System.Xml.XmlR eader.CreateRea derImpl(Stream input, XmlReaderSettin gs
settings, Uri baseUri, String baseUriStr, XmlParserContex t inputContext,
Boolean closeInput) +68
System.Xml.XmlR eader.Create(St ream input, XmlReaderSettin gs settings,
String baseUri) +37
System.Xml.XmlR eader.Create(St ream input, XmlReaderSettin gs settings) +30

Can you tell me what is happening here and how I might resolve it?

Many thanks
Andrew
Jul 19 '07 #1
6 17142
J055 wrote:
Hi

I have the following code. I upload an XML file using the FileUpload object,
store the stream in a session so the user gets the chance to confirm some
options then pass the stream from the Session to an XmlReader.

if (performImport == false)
{
Session["__xmlImportFil e"] = fileUpload1.Fil eContent;
As you haven't created the stream yourself, you don't have control over
when the stream is disposed. When the FileUpload control is disposed, it
also disposes the stream.

If you need to store something in a session variable, you have to store
the actual content of the file, not the stream used to read it.

Generally it's a bad idea to store large objects in session variables,
though. It uses up memory, and that is a limited resource on the server.
You should consider other options for storing it.
//... some other code
}
else
{
if (Session["__xmlImportFil e"] != null)
{
Stream xmlFile = (Stream)Session["__xmlImportFil e"];
xmlFile.Positio n = 0;
// ... pass xmlFile to XmlReader
}
Session.Remove( "__xmlImportFil e");
}

This works fine on the Visual Studio web server.
No, not fine. You just got lucky (?) that it didn't blow up.
When I transfer the code to
an IIS web server I can only get the code to work if the uploaded file is
80Kb or less. Anything over that and I get an ObjectDisposedE xception
(Cannot access a closed file.) The size in bytes of the stream from the
session appears to be correct before the XmlReader is called.

[ObjectDisposedE xception: Cannot access a closed file.]
System.IO.__Err or.FileNotOpen( ) +56
System.IO.FileS tream.Seek(Int6 4 offset, SeekOrigin origin) +1945963
System.Web.Temp File.GetBytes(I nt32 offset, Int32 length, Byte[] buffer,
Int32 bufferOffset) +35
System.Web.Http RawUploadedCont ent.CopyBytes(I nt32 offset, Byte[] buffer,
Int32 bufferOffset, Int32 length) +112
System.Web.Http InputStream.Rea d(Byte[] buffer, Int32 offset, Int32 count)
+47
System.Xml.XmlT extReaderImpl.I nitStreamInput( Uri baseUri, String
baseUriStr, Stream stream, Byte[] bytes, Int32 byteCount, Encoding encoding)
+196
System.Xml.XmlT extReaderImpl.. ctor(Stream stream, Byte[] bytes, Int32
byteCount, XmlReaderSettin gs settings, Uri baseUri, String baseUriStr,
XmlParserContex t context, Boolean closeInput) +62
System.Xml.XmlR eader.CreateRea derImpl(Stream input, XmlReaderSettin gs
settings, Uri baseUri, String baseUriStr, XmlParserContex t inputContext,
Boolean closeInput) +68
System.Xml.XmlR eader.Create(St ream input, XmlReaderSettin gs settings,
String baseUri) +37
System.Xml.XmlR eader.Create(St ream input, XmlReaderSettin gs settings) +30

Can you tell me what is happening here and how I might resolve it?

Many thanks
Andrew
--
Göran Andersson
_____
http://www.guffa.com
Jul 19 '07 #2
As Goran indicated, you might want to try this approach, which stores the
contents (that's what you want anyway, right?):

Int32 fileLen;
// Get the length of the file.
fileLen = FileUpload1.Pos tedFile.Content Length;
// Create a byte array to hold the contents of the file.
Byte[] Input = new Byte[fileLen];
// Initialize the stream to read the uploaded file.
myStream = FileUpload1.Fil eContent;
// Read the file into the byte array.
myStream.Read(I nput, 0, fileLen);
// Store the byte array in Session
Session["__xmlImportFil eBytes"] = Input;

--Peter
Recursion: see Recursion
site: http://www.eggheadcafe.com
unBlog: http://petesbloggerama.blogspot.com
bogMetaFinder: http://www.blogmetafinder.com

"J055" wrote:
Hi

I have the following code. I upload an XML file using the FileUpload object,
store the stream in a session so the user gets the chance to confirm some
options then pass the stream from the Session to an XmlReader.

if (performImport == false)
{
Session["__xmlImportFil e"] = fileUpload1.Fil eContent;
//... some other code
}
else
{
if (Session["__xmlImportFil e"] != null)
{
Stream xmlFile = (Stream)Session["__xmlImportFil e"];
xmlFile.Positio n = 0;
// ... pass xmlFile to XmlReader
}
Session.Remove( "__xmlImportFil e");
}

This works fine on the Visual Studio web server. When I transfer the code to
an IIS web server I can only get the code to work if the uploaded file is
80Kb or less. Anything over that and I get an ObjectDisposedE xception
(Cannot access a closed file.) The size in bytes of the stream from the
session appears to be correct before the XmlReader is called.

[ObjectDisposedE xception: Cannot access a closed file.]
System.IO.__Err or.FileNotOpen( ) +56
System.IO.FileS tream.Seek(Int6 4 offset, SeekOrigin origin) +1945963
System.Web.Temp File.GetBytes(I nt32 offset, Int32 length, Byte[] buffer,
Int32 bufferOffset) +35
System.Web.Http RawUploadedCont ent.CopyBytes(I nt32 offset, Byte[] buffer,
Int32 bufferOffset, Int32 length) +112
System.Web.Http InputStream.Rea d(Byte[] buffer, Int32 offset, Int32 count)
+47
System.Xml.XmlT extReaderImpl.I nitStreamInput( Uri baseUri, String
baseUriStr, Stream stream, Byte[] bytes, Int32 byteCount, Encoding encoding)
+196
System.Xml.XmlT extReaderImpl.. ctor(Stream stream, Byte[] bytes, Int32
byteCount, XmlReaderSettin gs settings, Uri baseUri, String baseUriStr,
XmlParserContex t context, Boolean closeInput) +62
System.Xml.XmlR eader.CreateRea derImpl(Stream input, XmlReaderSettin gs
settings, Uri baseUri, String baseUriStr, XmlParserContex t inputContext,
Boolean closeInput) +68
System.Xml.XmlR eader.Create(St ream input, XmlReaderSettin gs settings,
String baseUri) +37
System.Xml.XmlR eader.Create(St ream input, XmlReaderSettin gs settings) +30

Can you tell me what is happening here and how I might resolve it?

Many thanks
Andrew
Jul 19 '07 #3
when the request completes, the stream is closed, so storing in session
is useless. if small, you could read the stream into sring, or into a
dom and store in session

-- bruce (sqlwork.com)

J055 wrote:
Hi

I have the following code. I upload an XML file using the FileUpload object,
store the stream in a session so the user gets the chance to confirm some
options then pass the stream from the Session to an XmlReader.

if (performImport == false)
{
Session["__xmlImportFil e"] = fileUpload1.Fil eContent;
//... some other code
}
else
{
if (Session["__xmlImportFil e"] != null)
{
Stream xmlFile = (Stream)Session["__xmlImportFil e"];
xmlFile.Positio n = 0;
// ... pass xmlFile to XmlReader
}
Session.Remove( "__xmlImportFil e");
}

This works fine on the Visual Studio web server. When I transfer the code to
an IIS web server I can only get the code to work if the uploaded file is
80Kb or less. Anything over that and I get an ObjectDisposedE xception
(Cannot access a closed file.) The size in bytes of the stream from the
session appears to be correct before the XmlReader is called.

[ObjectDisposedE xception: Cannot access a closed file.]
System.IO.__Err or.FileNotOpen( ) +56
System.IO.FileS tream.Seek(Int6 4 offset, SeekOrigin origin) +1945963
System.Web.Temp File.GetBytes(I nt32 offset, Int32 length, Byte[] buffer,
Int32 bufferOffset) +35
System.Web.Http RawUploadedCont ent.CopyBytes(I nt32 offset, Byte[] buffer,
Int32 bufferOffset, Int32 length) +112
System.Web.Http InputStream.Rea d(Byte[] buffer, Int32 offset, Int32 count)
+47
System.Xml.XmlT extReaderImpl.I nitStreamInput( Uri baseUri, String
baseUriStr, Stream stream, Byte[] bytes, Int32 byteCount, Encoding encoding)
+196
System.Xml.XmlT extReaderImpl.. ctor(Stream stream, Byte[] bytes, Int32
byteCount, XmlReaderSettin gs settings, Uri baseUri, String baseUriStr,
XmlParserContex t context, Boolean closeInput) +62
System.Xml.XmlR eader.CreateRea derImpl(Stream input, XmlReaderSettin gs
settings, Uri baseUri, String baseUriStr, XmlParserContex t inputContext,
Boolean closeInput) +68
System.Xml.XmlR eader.Create(St ream input, XmlReaderSettin gs settings,
String baseUri) +37
System.Xml.XmlR eader.Create(St ream input, XmlReaderSettin gs settings) +30

Can you tell me what is happening here and how I might resolve it?

Many thanks
Andrew

Jul 19 '07 #4
Peter Bromberg [C# MVP] wrote:
As Goran indicated, you might want to try this approach, which stores the
contents (that's what you want anyway, right?):

Int32 fileLen;
// Get the length of the file.
fileLen = FileUpload1.Pos tedFile.Content Length;
// Create a byte array to hold the contents of the file.
Byte[] Input = new Byte[fileLen];
// Initialize the stream to read the uploaded file.
myStream = FileUpload1.Fil eContent;
// Read the file into the byte array.
myStream.Read(I nput, 0, fileLen);
Oops! ;)

The Read method returns the actual number of bytes read, which may be
less than the number of bytes requested. You have to loop until you have
read all the bytes, i.e. until Read returns zero.
// Store the byte array in Session
Session["__xmlImportFil eBytes"] = Input;

--Peter
Recursion: see Recursion
site: http://www.eggheadcafe.com
unBlog: http://petesbloggerama.blogspot.com
bogMetaFinder: http://www.blogmetafinder.com
--
Göran Andersson
_____
http://www.guffa.com
Jul 19 '07 #5
Hi Andrew,

As other members have mentioned, storing the Stream object directly in
Session is not a safe approach as you can not predict or confirm when the
stream will be closed or disposed. And the behavior vary much between VS
2005 web test server and IIS hosting context. For your scenario, you can
consider the following approachs:

1. Read out the actual binary content(byte array) from the stream and store
the binary content into session state. However, as others have said, this
is not quite a good way since it will cause session state memory
pressure(when there is many large files stored at the same time).

2. You can consider save uploaded file into a temp dir(in a temp file). And
in the session state, you simply store the path and file name of the temp
file.

How do you think?

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead
This posting is provided "AS IS" with no warranties, and confers no rights.


Jul 20 '07 #6
Hi

Thanks to everyone for there assistance. It makes sense to me now about the
stream being disposed of outside my control. The reason I thought it OK to
store a stream in a Session is simply because it's is a very occasional
demand on the system for our application.

I've decided to store the file on disk, however. I found the
Path.GetTempFil eName method very useful for this.

Many thanks
Andrew
"Steven Cheng[MSFT]" <st*****@online .microsoft.comw rote in message
news:oT******** ******@TK2MSFTN GHUB02.phx.gbl. ..
Hi Andrew,

As other members have mentioned, storing the Stream object directly in
Session is not a safe approach as you can not predict or confirm when the
stream will be closed or disposed. And the behavior vary much between VS
2005 web test server and IIS hosting context. For your scenario, you can
consider the following approachs:

1. Read out the actual binary content(byte array) from the stream and
store
the binary content into session state. However, as others have said, this
is not quite a good way since it will cause session state memory
pressure(when there is many large files stored at the same time).

2. You can consider save uploaded file into a temp dir(in a temp file).
And
in the session state, you simply store the path and file name of the temp
file.

How do you think?

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead
This posting is provided "AS IS" with no warranties, and confers no
rights.


Jul 23 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2877
by: Muppy | last post by:
I've created a page with a form to upload files: <h1>Upload di un file</h1> <form enctype="multipart/form-data" method="post" action="do_upload1.php"> <p><strong>File da trasferire:</strong><br> <input type="hidden" name="MAX_FILE_SIZE" value="1000000"> <input type="file" name="img1" size="30"> </p> <p> <input type="submit" name="submit" value="Upload File">
5
5467
by: Dave Smithz | last post by:
Hi There, I have a PHP script that sends an email with attachment and works great when provided the path to the file to send. However this file needs to be on the same server as the script. I want to develop a webpage where people can send attachments that are stored on their local PC.
1
2827
by: Selena | last post by:
I have vb.net windows application which need to upload file to server. It can run properly without using VPN. How can I run it with VPN? Is there any components or code to upload file? Or is there any method to get Ip assigned by VPN? Thank you.
9
7301
by: david | last post by:
I have a class with some business-logic and with every roundtrip, I need an instance of this class, so I have to create it, every time again. That doesn't seem very efficient. I thought it would be 'better' to store an instance of this class in a session-variable, so it's available all the time and needs to be instanced only once. Is this, generally speaking, a good idea, storing objects in session-variables ? Do you guys ever use this...
4
11120
by: bienwell | last post by:
Hi all, I developed an web page in ASP.NET to upload file into the server. In the Web.config file, I declared <httpRuntime executionTimeout="1200" maxRequestLength="400000" /> The MAX length is 129M or more for each file upload. I have 2 files upload at the same time. Therefore, I set the timeout is 20min and the size of file upload is 390MB (400,000 KBytes).
2
1713
by: suresh_nsnguys | last post by:
Hi, I am working in digital signage application where user can upload image,flash and movie files .and later thay can view the uploaded files in digital LCD screen. I am facing 1 issue.i able to store the uploaded files in 1 single directory in server.but i am afraid that how many files will be stored in 1 single directory.Bcz in the future,my upload files can reach say1 lakth.i am not sure whether a single directory can handle...
4
9182
by: google.com | last post by:
Hi there! I've been digging around looking for a sample on how to upload a file without user action. I found the following article covering the area: http://www.motobit.com/tips/detpg_uploadvbaie/ It describes the vba code required to handle a very simple upload form:
1
254
by: Sam | last post by:
Hi all, We have an old web application written in java and we want to convert this application to .net. this app stores straight html content forms in our database. These forms then get loaded based on each customer id in the request. The problem I'm facing right now is that, when a form has an "user upload" file option, I don't find a way in .Net to save the "user upload" file on our server from these html form without rebuilding...
2
9436
by: lka527 | last post by:
I am trying to make a site available for someone to *upload* certain type of text file (.txt) that can be parsed by written code. the upload file is available on the main site but I need this to result in different page on the right as someone clicks on SUBMIT with one's file attached. The uploaded file by clicking submit button should be PARSED on the right side of the page but when I click on the submit with the file now, it goes to the local...
0
8995
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8832
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9558
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9378
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9331
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8250
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6077
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2216
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.