Click here to Skip to main content
15,885,948 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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

1 solution

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

C#
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
 
Share this answer
 
v2
Comments
Member 9291223 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 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 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 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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900