Solved

Why does System.IO.Path.GetExtension crash server?

Posted on 2006-07-04
31
332 Views
Last Modified: 2008-02-01
Hi,

I have code that looks like this:

<html>
<body>
<input id="txtFilePath" type="file" style="width:300px;" runat="server" />
</body>
</html>

then in my ASP.NET 1.1 C# code i have this:
string fileToUploadExtension = System.IO.Path.GetExtension(txtFilePath.Value).ToLower();


What i am trying to do, is get the file extension of the specified text.  for exampel, if someone put in "helloWorld.DOC" i would want to get ".DOC"..

however, if someone trys to put in a ZIP file, or a very large PSD file, the web application crashes and i get an IE error that looks like this:

The page cannot be displayed
The page you are looking for is currently unavailable. The Web site might be experiencing technical difficulties, or you may need to adjust your browser settings.


Is there a better way to get the file extension?

0
Comment
Question by:alexthecodepoet
  • 16
  • 15
31 Comments
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17038496
Workaroud:
It's in VB but should be easy to understand:

      Dim myExt As String
      Dim myInput As String

      myInput = "My.File.doc"
      myExt = myInput.Split(".")(myInput.Split(".").Length - 1)

If you want I could try to convert into C#

0
 

Author Comment

by:alexthecodepoet
ID: 17038508
yes please, C# would be most preferable

and, this will return the expected result, right?

For example: C:\folder.withDOTINTHEMIDDLE\newfile.jasldk.asld.DOC

will return .DOC

with your idea, right?
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17038519
That's what http://www.developerfusion.co.uk/utilities/convertvbtocsharp.aspx returned me, but I doubt it will work

string myExt;
string myInput;
private object myInput = "My.File.doc";
private object myExt = myInput.Split(".")(myInput.Split(".").Length - 1);

The idea is this:
1. Split your input string into array separating it with a "." (dot) char
2. Get the last item from array. That will be your extention

Hope this will help
0
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17038544
Here you go:

                  string myInput;
                  string myExt;
                  myInput="My.Test.File.doc";
                  myExt=myInput.Split(new char[]{'.'})[myInput.Split(new char[]{'.'}).Length-1];
                  MessageBox.Show(myExt);

Tested on .NET v1.1, but I think it'll be the same on .NET 2.0
Returns 'doc'

:)
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17038574
A slight modification:

            string myInput;
                  string myExt;
                  myInput="sss";
                  myExt=myInput.Split(new char[]{'.'})[myInput.Split(new char[]{'.'}).Length-1];
                  // if extention equals to input that means there is no extention
                  if (myExt==myInput)
                                          myExt="";
                  MessageBox.Show(myExt);
0
 

Author Comment

by:alexthecodepoet
ID: 17038591
Ugh, so close.

Thanks for all of the udpates :) you are right.. this does work, but just like the other 2 algorithms i try to do, i always get this problem if i try to input .zip or .psd

:

The page cannot be displayed
The page you are looking for is currently unavailable. The Web site might be experiencing technical difficulties, or you may need to adjust your browser settings.



Any idea why?  
0
 

Author Comment

by:alexthecodepoet
ID: 17038605
its interesting,

even doing this will cause the site to bug out:

        fileToUploadFilePath = txtFilePath.Value;

        Response.Write(fileToUploadFilePath);


if i try to put a ZIp file in the path, it will cause that error..
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17038620
Seems like problems are somewhere else, not in extracting extention.

Try to comment everything below the extention extraction code an see if is this is causing problems. If not then uncomment line by line, block by block and you'll know where the problem is. My code is only a manipulation with strings and it should not act like working with ".doc" string and hanging with ".zip" string.
0
 

Author Comment

by:alexthecodepoet
ID: 17038624
could this have something to do with using <input type="file">
?

The reason i ask is because if i do <asp:textbox runat="server"...>

and then try to get the text out of that, it wont crash the system.

however,

<input type="file">

does crash..

so i wonder, does the real problem lye within <input type="file">?
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17038625
Show all the code
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17038645
<input type="file" runat="server">

;)
0
 

Author Comment

by:alexthecodepoet
ID: 17038656
what about it? :) should it be there, or.. should it not :)
0
 

Author Comment

by:alexthecodepoet
ID: 17038668
the reason i ask is because in my code, i have runat="server" there already
0
 

Author Comment

by:alexthecodepoet
ID: 17038673
This is all of my code:

you'll notice, try "browsing" for a very large zip file, it will crash the web app

then try doing a .html file or something, it wont crash..


<%@ Page Language="C#" debug="true" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Threading" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>


<script runat="server">
   
 
    void forwardStep2(object s, EventArgs e)
    {
        /* get the file extension and see if it is an approved type: .doc, .xls, .ppt, .htm,
         * .html, .asp, .aspx */

        string fileToUploadFilePath = "";
        fileToUploadFilePath = txtFilePath.Value;

        Response.Write(fileToUploadFilePath);

    }

</script>

<html>
<title>
test</title>
<body>
<form id="Form1" runat="server">

File Path: <input id="txtFilePath" type="file" style="width:300px;" runat="server" />
<br />
<br />

<asp:button id="btnNext" onClick="forwardStep2" text="next" runat="server" />

</form>

</body>
</html>


0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17038684
In aspx file:
<input id="myUploadCtrl" type="file" runat="server">

Then in code behind file in initialize component sub:
Protected myUploadCtrl As System.Web.UI.HtmlControls.HtmlInputFile

The "Protected..." stuff in VB again :) but I guess you'll manage how to make this declaration.

Only having this setup in your aspx and codebehind you'll be able to reference you're upload control in your code
0
 

Author Comment

by:alexthecodepoet
ID: 17038702
sooo close

by the way, you are sort of answering 2 questions (1), why it crashes, and 2) the file format.  so once we are done, i am going to open up a new question about the file format, let you paste your answer, and give you points for that one, too.  that way you get credit for both questions

but now i get this error:'

The class 'ASP.delete_aspx' already contains a definition for 'txtFilePath'

Source Error:

 

Line 9:  <script runat="server">
Line 10:    
Line 11:     protected HtmlInputFile txtFilePath;

 
.....

<input id="txtFilePath" type="file" style="width:300px;" runat="server" />
0
 

Author Comment

by:alexthecodepoet
ID: 17038707
by the way, i am not using code behind files, everything is done on the same page

<script runat="server">

</script>
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17038713
Try using
fileToUploadFilePath = txtFilePath.PostedFile.FileName;


!!! AND !!! Very important

<form id="Form1" method="post" encType="multipart/form-data" runat="server">

The encType attribute lets you upload files
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17038724
Well, yeah, I see... We are passing each other with questions and answers :)
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17038743
http://www.w3schools.com/aspnet/control_htmlinputfile.asp

Here you'll find a sample with the upload control with no codebehind file. Analyze sample carefuly

P.S. Don't open new topic. It's not points I'm here for ;)
0
 

Author Comment

by:alexthecodepoet
ID: 17038747
even with these changes (PostedFile.FileName) and encType.., i get the same problem:

<script runat="server">
   

 
    void forwardStep2(object s, EventArgs e)
    {
        /* get the file extension and see if it is an approved type: .doc, .xls, .ppt, .htm,
         * .html, .asp, .aspx */

        string fileToUploadFilePath = "";
        fileToUploadFilePath = txtFilePath.PostedFile.FileName;

        Response.Write(fileToUploadFilePath);

    }

</script>

<html>
<title>
test</title>
<body>
<form id="Form1" encType="multipart/form-data" runat="server">

File Path: <input id="txtFilePath" type="file" style="width:300px;" runat="server" />
<br />
<br />

<asp:button id="btnNext" onClick="forwardStep2" text="next" runat="server" />

</form>

</body>
</html>

I still get the "this page can not be displayed error"

0
 

Author Comment

by:alexthecodepoet
ID: 17038761
LOL,

Even using the w3 schools example, selecting a large zip will crash the page

:(
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17038781
LARGE??? How large? I don't know exactly but I think 1MB is a limit
0
 

Author Comment

by:alexthecodepoet
ID: 17038787
well, the zip file is 32 MB

but thats the point.. see, i am trying to validate certain file types.  so i only want users to be able to be able to upload, say, HTML files.

but, if a user does try to input a .ZIP file, i need to catch it, and say that file type isn't allowed.

is that possible?
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17038804
OK, let's try this:

try
{
string fileToUploadFilePath = "";
        fileToUploadFilePath = txtFilePath.PostedFile.FileName;

        Response.Write(fileToUploadFilePath);
}

catch (Exception e)
{
Response.Write(e.Message);
}


In a "catch" block you can do a validation an throw a message to a user depending on exception
0
 
LVL 14

Accepted Solution

by:
Ramuncikas earned 500 total points
ID: 17038826
What a complicated situation, uh? :))
Read this - sould be helpfull:
http://www.standardio.org/article.aspx?id=213
0
 

Author Comment

by:alexthecodepoet
ID: 17038853
ill try the standardio.org one..

but its crazy, even using try and catch statements, the system sitll crashes :(
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17038866
It because of file size limit. You'll find about it in the article.
0
 

Author Comment

by:alexthecodepoet
ID: 17038905
Well, it looks like on this Independence day, i will be celebrating freedom from max file sizes, too :)

If you dont mind, do you understand what the author means by this?
The important thing is that, upon redirecting the user, the server discards the input stream and you don't have a 300 meg file in memory on your server.


That means that, since the user is redirected, you dont have a 300 meg file laying around.. right?

And also,

What would you recomend having the file limit as?  8  megs?


Thank you so much!  I wish i could tell you how much i appreciate your help.  This is the best ive ever had!
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17040277
>>>The important thing is that, upon redirecting the user, the server discards the input stream and you don't have a 300 meg file in memory on your server.
Suppose you have a form with upload control. Yes, like your one. Suppose me comming to your page and selecting a file of whatever size. Whether it is a file of 1K size or it is a file of 100MB size, your form has to get all of the content of your form (and a file too) to be able to process steps coded in a function whitch rose a page postback. So that meens that a file is downloaded to a servers cache somewhere. But as I understood (by quick reading) from author's words if file exceeds a size limit, then .NET engine goes somehow crazy and none of error handling steps in the same page help.
A good thing is to use global.asax file where you can catch Application_BeginRequest event. There you can get the size of the the request content WITHOUT downoading all the content to server. And IF content exceeds maxfilesize limit you do the redirect whitch (I suppose) drops previuos request.

>>>That means that, since the user is redirected, you dont have a 300 meg file laying around.. right?
Well...laying around. I don't think that all files uploaded to server are laying in their native format as separate files. As you upload server gets some kind of streams whitch have their lifetime. Server manages these streams itself and I don't think that If someone was to upload a 300 MB file to your app and ended with Server unavailable error I don't think that your server's HDD space decreased by 300 MB until you do a manual clean-up. It's all up to server. How exactly all this process flows I don't know.

Thanks for points
Good luck
0
 

Author Comment

by:alexthecodepoet
ID: 17040288
Awesome, thanks for the explanataion.

after i implemented the solution described, i found another problem: this whole idea doesn't work on IIS 5.1 on Windows XP --but it will work on other machines :( So i spent 2 hours trying to develop it locally, with no success (i think i tried 10 different code examples).. then i tried uploading it to a real server, and it worked

weird, huh? :)  But apparently, even MS knows about the issue and says that it is bug with IIS 5.1 on Windows XP
No help needed here though, as it will work fine on a real server :)


Thanks again for all of the help
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question