Solved

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

Posted on 2006-07-04
31
310 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 14

Expert Comment

by:Ramuncikas
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Show all the code
0
 
LVL 14

Expert Comment

by:Ramuncikas
Comment Utility
<input type="file" runat="server">

;)
0
 

Author Comment

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

Author Comment

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

Author Comment

by:alexthecodepoet
Comment Utility
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
Comment Utility
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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:alexthecodepoet
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Well, yeah, I see... We are passing each other with questions and answers :)
0
 
LVL 14

Expert Comment

by:Ramuncikas
Comment Utility
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
Comment Utility
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
Comment Utility
LOL,

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

:(
0
 
LVL 14

Expert Comment

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

Author Comment

by:alexthecodepoet
Comment Utility
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
Comment Utility
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
Comment Utility
What a complicated situation, uh? :))
Read this - sould be helpfull:
http://www.standardio.org/article.aspx?id=213
0
 

Author Comment

by:alexthecodepoet
Comment Utility
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
Comment Utility
It because of file size limit. You'll find about it in the article.
0
 

Author Comment

by:alexthecodepoet
Comment Utility
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
Comment Utility
>>>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
Comment Utility
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

762 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now