ali raza

C#, .Net ,Asp.net and my thoughts

Monthly Archives: May 2007

Code to upload file in c#

protected void btnUploadFile_Click(object sender, EventArgs e){

string sFilename = “”;// Check file size (mustn’t be 0)

HttpPostedFile myFile = FileUploading.PostedFile;int nFileLen = myFile.ContentLength;

if (nFileLen==0){

lblMsg.Text=“No valid file for upload.”;// return;

}

else

{

byte[] myData=new Byte[nFileLen];myFile.InputStream.Read(myData, 0, nFileLen);

sFilename=System.Guid.NewGuid().ToString().Replace(“-“, “”)+“_”+System.IO.Path.GetFileName(myFile.FileName);// Save the stream to disk

System.IO.FileStream newFile=new System.IO.FileStream(Server.MapPath(TaskManagementTool.Config.Path+sFilename), System.IO.FileMode.Create);newFile.Write(myData, 0, myData.Length);

newFile.Close();

TaskManagementTool.TaskDB taskDB=new TaskManagementTool.TaskDB();taskDB.AddUploadedFile(Convert.ToInt32(lblTaskId.Text), sFilename, ckIsPrivate.Checked);ShowUploadFiles();

}

// Read file into a data stream

//return sFilename;

}

downloading file in c#

private void DownloadFile(String strFileName){FileStream fs;

string strContentType;string strPath=TaskManagementTool.Config.Path.ToString();

//Dim strFileName As String = Request.QueryString(”DocumentFile”)fs = File.Open(Server.MapPath(strPath + strFileName), FileMode.Open);

Byte[] bytBytes = new byte[fs.Length] ; // Write the stream to the byte array

fs.Read(bytBytes, 0, Convert.ToInt32(fs.Length)); // Close the file stream to release the resource

fs.Close();Response.AddHeader(“Content-disposition”, “attachment; filename=”+strFileName);

// Next we need to add some header information.// These headers will tell the browser what it needs to do

// with the content we’re serving

Response.ContentType = “application/octet-stream”;// Now our headers are added, we can serve the content.// To do this, we use the BinaryWrite() method of the server object

// This successfully streams our external file to the user,

// despite the fact that the file doesn’t exist

// anywhere inside the web application

Response.BinaryWrite(bytBytes);// Call Response.End() so that no more// content goes through to the client.

Response.End();}

}