Link to home
Start Free TrialLog in
Avatar of alexthecodepoet
alexthecodepoet

asked on

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

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?

Avatar of Ramuncikas
Ramuncikas
Flag of Lithuania image

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#

Avatar of alexthecodepoet
alexthecodepoet

ASKER

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?
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
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'

:)
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);
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?  
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..
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.
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">?
Show all the code
<input type="file" runat="server">

;)
what about it? :) should it be there, or.. should it not :)
the reason i ask is because in my code, i have runat="server" there already
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>


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
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" />
by the way, i am not using code behind files, everything is done on the same page

<script runat="server">

</script>
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
Well, yeah, I see... We are passing each other with questions and answers :)
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 ;)
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"

LOL,

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

:(
LARGE??? How large? I don't know exactly but I think 1MB is a limit
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?
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
ASKER CERTIFIED SOLUTION
Avatar of Ramuncikas
Ramuncikas
Flag of Lithuania image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ill try the standardio.org one..

but its crazy, even using try and catch statements, the system sitll crashes :(
It because of file size limit. You'll find about it in the article.
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!
>>>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
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