Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#3.0
I have ran into a situation where im able to download a file by specifying the file path but the issue is that the file is download in a unknown format. The code below shows the downloading process:
 
if (e.CommandName == "ViewFiles")
{
 
int index = Convert.ToInt32(e.CommandArgument);
 
GridViewRow row = gvunclassified.Rows[index];
 
string division = row.Cells[4].Text;
 
string filenames = row.Cells[1].Text;
 
string paths = @"NewFolder1" + "\\" + division + "\\" + "UnClassified" + "\\" + filenames;
string drive = @"C:\Website2\RecordsManagement";
string temppath = Path.Combine(drive, paths);
 

// The file path to download.
 
string filepath = temppath;
 
// The file name used to save the file to the client's system..
 
string filename = Path.GetFileName(filepath);
System.IO.Stream stream = null;
try
{
// Open the file into a stream.
stream = new FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
// Total bytes to read:
long bytesToRead = stream.Length;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
// Read the bytes from the stream in small portions.
while (bytesToRead > 0)
{
// Make sure the client is still connected.
if (Response.IsClientConnected)
{
// Read the data into the buffer and write into the
// output stream.
byte[] buffer = new Byte[10000];
int length = stream.Read(buffer, 0, 10000);
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
// We have already read some bytes.. need to read
// only the remaining.
bytesToRead = bytesToRead - length;
}
else
{
// Get out of the loop, if user is not connected anymore..
bytesToRead = -1;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
// An error occurred..
}
finally
{
if (stream != null)
{
stream.Close();
}
}
 
Any suggestion would be highly appreciated. Actually the most surprising part is that if I use google chrome as my browser then the file is downloaded in the right format but an unknown format file is download if I use IE or Mozilla firefox.
Posted 19-Nov-12 15:29pm

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Code to Download the File
 
 Response.ClearContent();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
                BinaryWriter bw = new BinaryWriter(Response.OutputStream);
                bw.Write(fileData);
                bw.Close();
                Response.ContentType = ReturnExtension(ext);
                Response.End();
 
Function used to get extension , make a function as common so u can use it in youer entire project , the below function i got it from Code Project some source i dont remember it now , and i am using it in my project it works perfectly for me in any browser
 
public string ReturnExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".htm":
            case ".html":
            case ".log":
                return "text/HTML";
            case ".txt":
                return "text/plain";
            case ".doc":
                return "application/ms-word";
            case ".tiff":
            case ".tif":
                return "image/tiff";
            case ".asf":
                return "video/x-ms-asf";
            case ".avi":
                return "video/avi";
            case ".zip":
                return "application/zip";
            case ".xls":
            case ".csv":
                return "application/vnd.ms-excel";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case "jpeg":
                return "image/jpeg";
            case ".bmp":
                return "image/bmp";
            case ".wav":
                return "audio/wav";
            case ".mp3":
                return "audio/mpeg3";
            case ".mpg":
            case "mpeg":
                return "video/mpeg";
            case ".rtf":
                return "application/rtf";
            case ".asp":
                return "text/asp";
            case ".pdf":
                return "application/pdf";
            case ".fdf":
                return "application/vnd.fdf";
            case ".ppt":
                return "application/mspowerpoint";
            case ".dwg":
                return "image/vnd.dwg";
            case ".msg":
                return "application/msoutlook";
            case ".xml":
            case ".sdxl":
                return "application/xml";
            case ".xdp":
                return "application/vnd.adobe.xdp+xml";
            default:
                return "application/octet-stream";
        }
    }
Let me know of it works
  Permalink  
v2
Comments
Member 9291223 at 19-Nov-12 22:12pm
   
thanks but what does fileData in this refers to.? bw.Write(fileData); Is this the file path for that particular file?
Member 9291223 at 19-Nov-12 22:19pm
   
Ya it does refers to the file path but sorry it didn't work out for me. Anyway thanks for the try. It was a good approach
Rickin Kane at 19-Nov-12 23:30pm
   
no issues , but just want to confirm , do you get filenames with extension , can you debug and see what is the file name being return when below code is executed
 
string filename = Path.GetFileName(filepath);
Member 9291223 at 20-Nov-12 14:10pm
   
Yes the piece of code will return the file name with extension and were as if only the file name is needed then I could have used Path.GetFileNameWithoutExtension(filepath);
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Maciej Los 245
1 OriginalGriff 210
2 Manfred R. Bihy 190
3 CHill60 180
4 _Amy 155
0 OriginalGriff 7,445
1 Sergey Alexandrovich Kryukov 6,157
2 Maciej Los 3,774
3 Peter Leow 3,448
4 CHill60 2,702


Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 19 Nov 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100