How to delete exist Excel file from uploaded folder? - c#

How to close excel file or delete from folder. I tried a lot but its not getting file there.so always throwing error : The process cannot access the file because it is being used by another process.How to solve it?
first time not throwing any error .going successfully uploaded but when next time with same file i am trying to upload then imideatly throwing an error before call upload method
creating excel
System.Data.DataTable dtexcel = new System.Data.DataTable();
dtexcel = BindComboWithParm("Get_Cols_Forexcelsheet");
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dtexcel, "Customer");
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Customer_Creation.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
checking for file
string FileName = "Customer_Creation";
string Paths = Server.MapPath("~/Uploads/") + FileName;
FileInfo file = new FileInfo(Paths);
if (file.Exists)
{
file.Delete();
}
upload event click
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
string FileName = "Customer_Creation";
string Paths = Server.MapPath("~/Uploads/") + FileName;
FileInfo file = new FileInfo(Paths);
if (file.Exists)
{
file.Delete();
}
if (FileUpload1.HasFile)
{
string excelPath = Server.MapPath("~/Uploads/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(excelPath);
ImporttoSQL(excelPath);
}
else
{
ScriptManager.RegisterClientScriptBlock(Page, typeof(System.Web.UI.Page), "ClientScript", "alert('Please select Excelsheet')", true);
return;
}
}
catch (Exception ex)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Exception Message: " + ex.Message.Replace("'", "").Replace("\"", "") + "');", true);
}
finally
{
ViewState["ExcelUploaded"] = "false";
}
}

I believe you just want to create a file, download it and then delete it once it has downloaded.
1. Create a custom FileHttpResponseMessage.
public class FileHttpResponseMessage : HttpResponseMessage
{
private readonly string filePath;
public FileHttpResponseMessage(string filePath)
{
this.filePath = filePath;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
Content.Dispose();
if(File.Exist(filePath))
File.Delete(filePath);
}
}
2. Create a function which will return generated file path. and use that path in below code :
public HttpResponseMessage Get()
{
var filePath = GetNewFilePath();//your function which will create new file.
var response = new FileHttpResponseMessage(filePath);
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(new FileStream(filePath, FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName ="YourCustomFileName"
};
return response;
}
3. Above code will delete file automatically once file will be served to user.

Right now it's difficult to say what is wrong. Most likely your file is still in use by some part of your program. Pleases check this link it contains useful information about how to debug it.
Your app has uploaded a file to a server. For this purpose it used managed resources (like FileStream etc). For some reason this file remains opened. Later your app tries to delete it when it's still in use. And you get this "File in use" exception.
What i'd recommend to do is try to delete this file directly and if this works then the problem is hidden somewhere in your 'upload part' of your code. If its not then problem is most likely lay with some external processes that uses this file.

Related

How to download files from google drive and save to a folder on local using C#

I need to download files from google drive and save to a folder on local using C#.
I have done as described in Google Developer API documentation but I'm getting the file with an invalid format. Please suggest how to download it.
I done:
downloadUrl = url of the file (eg: https://drive.google.com/uc?id=1ULNeKdDoCRmWgPPBW8-d1EGUZgqvA1Ul&export=download)<br/>
filename = some name with extension
private bool SaveToDir(string downloadUrl,string filename) {
string filePath = Server.MapPath("imports/");
bool resp = false;
DriveService ds = new DriveService();
Uri temp = new Uri(downloadUrl);
string fileId = HttpUtility.ParseQueryString(temp.Query).Get("id");
var req = ds.Files.Get(fileId.Trim());
var stream = new MemoryStream();
req.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress dp)=> {
switch (dp.Status)
{
case Google.Apis.Download.DownloadStatus.Downloading:
Message("downloading, please wait....");
break;
case Google.Apis.Download.DownloadStatus.Completed:
using (FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
stream.WriteTo(file);
Message("File Downloaded successfully.");
}
resp = true;
break;
case Google.Apis.Download.DownloadStatus.Failed:
Message("Failed to Download.");
resp = false;
break;
}
};
req.Download(stream);
In my opinion the process is this:
export the file to pdf;
save the pdf in a folder of the server,
download the pdf locally.
First
public static void ExportFileToPdf(string fileId, string newFileName)
{
DriveService service = (DriveService)GetService();
string FolderPath = HostingEnvironment.MapPath("~/Myfolder/");
// F: effettua la richiesta
FilesResource.ExportRequest request = service.Files.Export(fileId, "application/pdf");
string FilePath = Path.Combine(FolderPath, newFileName);
string fPath = FilePath;
MemoryStream outputStream = new MemoryStream();
request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) =>
{
switch (progress.Status)
{
case DownloadStatus.Downloading:
{
Console.WriteLine(progress.BytesDownloaded);
break;
}
case DownloadStatus.Completed:
{
Console.WriteLine("Download complete.");
SaveStream(outputStream, fPath);
break;
}
case DownloadStatus.Failed:
{
Console.WriteLine("Download failed.");
break;
}
}
};
request.Download(outputStream);
DownloadFile("~/Myfolder/", newFileName);
}
Second
private static void SaveStream(MemoryStream stream, string FilePath)
{
using (FileStream file = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite))
{
stream.WriteTo(file);
}
}
Third
private static void DownloadFile(string folderName, string fileName)
{
HttpResponse response = HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
response.TransmitFile(HostingEnvironment.MapPath(folderName+fileName));
response.Flush();
response.End();
}
If we need to download important documents like receipts or invoices, we can also implement a control to verify if the file is already present in the server, instead of continuos pdf export.
If the file type is a google document type then you need to preform an export you cant just use the downloadurl link
var fileId = "1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo";
var request = driveService.Files.Export(fileId, "application/pdf");
var stream = new System.IO.MemoryStream();
// Add a handler which will be notified on progress changes.
// It will notify on each chunk download and when the
// download is completed or failed.
request.MediaDownloader.ProgressChanged +=
(IDownloadProgress progress) =>
{
switch (progress.Status)
{
case DownloadStatus.Downloading:
{
Console.WriteLine(progress.BytesDownloaded);
break;
}
case DownloadStatus.Completed:
{
Console.WriteLine("Download complete.");
break;
}
case DownloadStatus.Failed:
{
Console.WriteLine("Download failed.");
break;
}
}
};
request.Download(stream);
void SaveStream(System.IO.MemoryStream stream, string saveTo)
{
using (System.IO.FileStream file = new System.IO.FileStream(saveTo, System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
stream.WriteTo(file);
}
}
// code here
SaveStream( dwnldstream, "C:\\Users\\thulfiqar\\Downloads\\photo.jpg");
please refer to this tutorial and note that "stream" in your code is corresponding to "dwnldstream" in my code.

How can i download a file on a button's onClick event in C#?

Im trying to download a file on my button's onClick event in C# anyone got any info on this?
Ok so to the people who wanted me to be a litle more specific im working in visual studio 2015 windows forms c#.
If you are using MVC then you can try the following code it is working for me :
#region Download File ==>
public ActionResult downloadfile(string Filename, string MIMEType)
{
try
{
string file_name = "/Files/EvidenceUploads/" + Filename;
string contentType = "";
//Get the physical path to the file.
string FilePath = Server.MapPath(file_name);
string fileExt = Path.GetExtension(file_name);
contentType = MIMEType;
//Set the appropriate ContentType.
Response.ContentType = contentType;
Response.AppendHeader("content-disposition", "attachment; filename=" + (new FileInfo(file_name)).Name);
//Write the file directly to the HTTP content output stream.
Response.WriteFile(FilePath);
Response.End();
return View(FilePath);
}
catch
{
Response.End();
return View();
//To Do
}
}
#endregion
If you are not using MVC please refer following code:
#region Download File ==>
public void downloadfile(string Filename, string MIMEType)
{
try
{
string file_name = "/Files/EvidenceUploads/" + Filename;
string contentType = "";
//Get the physical path to the file.
string FilePath = Server.MapPath(file_name);
string fileExt = Path.GetExtension(file_name);
contentType = MIMEType;
//Set the appropriate ContentType.
Response.ContentType = contentType;
Response.AppendHeader("content-disposition", "attachment; filename=" + (new FileInfo(file_name)).Name);
//Write the file directly to the HTTP content output stream.
Response.WriteFile(FilePath);
Response.End();
}
catch
{
Response.End();
//To Do
}
}
#endregion
Hope its help to you.
First, question is too broad (Not specified is that desktop or Web application) . Lets suggest that you mean Winforms, then quick answer is DownloadFileAsync ( Async in order to keep UI interactive for user):
private void Download_Click(object sender, RoutedEventArgs e)
{
using (WebClient wc = new WebClient())
{
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
wc.DownloadFileAsync(new System.Uri("http://url"),
"Result location");
}
}
It`s a good idea to have a progress bar:
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
Using ASP.NET MVC I used the following within a controller to return a file from the content/Audiofile folder.
/// <summary>
/// The download action returns the file as a File download.
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
[AllowAnonymous]
public FilePathResult Download(String filename)
{
String myfile = Path.Combine(HttpContext.Server.MapPath("~/Content/audiofiles/"), filename);
return File(myfile, System.Net.Mime.MediaTypeNames.Application.Octet, filename);
}

FIle Downloading asp.net

I am trying to download a file using a button on asp.net, but the button gives me the webform aspx as the the downloaded file in my case DownloadFileTest.apsx. I needed to download the right file. This might help I the uploaded file in my solution explorer doesn't show up either. But it shows up if I access it inside the folder of my project. Here is the code
protected void Button1_Click(object sender, EventArgs e)
{
string filename = TextBox1.Text;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("content-diposition", "attach;filename" + filename);
Response.TransmitFile(Server.MapPath("~/CustomerFiles/" + filename));
Response.End();
}
This is the code I use to download file, make sure fuldFilNavn contains the full path of the file:
public static void DownloadFil(string fuldFilNavn)
{
HttpContext context = HttpContext.Current;
context.Response.ClearHeaders();
context.Response.ClearContent();
string filNavn = Uri.EscapeDataString(Path.GetFileName(fuldFilNavn)).Replace("+", "%20");
context.Response.AppendHeader("Content-Disposition", "attachment;filename*=utf-8''" + filNavn);
context.Response.AppendHeader("Last-Modified", File.GetLastWriteTimeUtc(fuldFilNavn).ToString("R"));
context.Response.ContentType = "application/octet-stream";
context.Response.AppendHeader("Content-Length", new FileInfo(fuldFilNavn).Length.ToString());
context.Response.TransmitFile(fuldFilNavn);
context.Response.End();
}
This will download files with unicode characters in the filename!
You may try the following ASP.NET/C# code snippet:
internal static void Download(string FileName)
{
HttpResponse _response = HttpContext.Current.Response;
FileStream _fileStream;
byte[] _arrContentBytes;
try
{
// clear response obj
_response.Clear();
// clear content of response obj
_response.ClearContent();
// clear response headers
_response.ClearHeaders();
// enable response buffer
_response.Buffer = true;
// specify response content
_response.ContentType = ContentType;
_response.StatusCode = 206;
_response.StatusDescription = "Partial Content";
// create FileStream: IMPORTANT - specify FileAccess.Read
_fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
// Bytes array size= (int)_fs.Length;
_arrContentBytes = new byte[(int)_fileStream.Length];
// read file into bytes array
_fileStream.Read(_arrContentBytes, 0, (int)_fileStream.Length);
// add response header
_response.AddHeader("content-disposition", "attachment;filename=" + FileName);
// ACTUAL PROCEDURE: use BinaryWrite to download file
_response.BinaryWrite(_arrContentBytes);
// ALTERNATIVE: TransmitFile
//_response.TransmitFile(filePath);
// close FileStream
_fileStream.Flush();
_fileStream.Close();
_response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch { }
finally
{
_fileStream = null;
_arrContentBytes = null;
}
}
In order to get the root folder and full path you may use Server.MapPath as in your original solution or the following line for better performance:
// get the root dir; fast
string _root = AppDomain.CurrentDomain.BaseDirectory;
This solution has been tested/implemented in the actual web app (http://taxiom.com/Manual_Payday.aspx) - refer to the "Download" button in the upper-right corner of the page for the demo. Hope this may help.

not able to export excel from gridview

this is my code:
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
try
{
DataTable dtbl = (DataTable)ViewState["dtbl"];
string path = "E:\\shubby" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + ".xls";
FileInfo fi = new FileInfo(path);
StringWriter sw = new StringWriter();
HtmlTextWriter htmltw = new HtmlTextWriter(sw);
DataGrid grdCrew = new DataGrid();
grdCrew.DataSource = dtbl;
grdCrew.DataBind();
grdCrew.RenderControl(htmltw);
string directory = path.Substring(0, path.LastIndexOf("\\"));// GetDirectory(Path);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
System.IO.StreamWriter vw = new System.IO.StreamWriter(path, true);
sw.ToString().Normalize();
vw.Write(sw.ToString());
vw.Flush();
vw.Close();
WriteAttachment(fi.Name, "application/vnd.ms-excel", sw.ToString());
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public static void WriteAttachment(string FileName, string FileType, string content)
{
HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.ClearHeaders();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.ContentType = FileType;
Response.Write(content);
Response.End();
}
I have seperate file for business logic and stored procedures, everything is working fine, its just the excel export that i am facing trouble with,
the error that i am getting is the exception that says "A required privilege is not held by the client"...
please help

I made csv file on the server - how can I let the client download this file?

I have made csv on the server like this:
string Expath = #"d:\A.csv";
protected void Button3_Click(object sender, EventArgs e)
{
FileStream FS = null;
StreamWriter SW = null;
try
{
FS = new FileStream(Expath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
SW = new StreamWriter(FS, Encoding.Default);
SW.WriteLine("Test");
SW.WriteLine("1,2,3,4,5");
}
catch { }
finally
{
if (SW != null)
{
SW.Close();
FS.Close();
}
}
}
is it correct to make this file on d: on the server? if not where is better to place hem?
how do to that the client can download this file after he made it? (asp.net C#)
You could use this code to push the file to browser.
private void PushToBrowser(string FilePath, byte[] Data)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BufferOutput = true;
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ContentType = #"application/csv";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(FilePath));
HttpContext.Current.Response.OutputStream.Write(Data, 0, Data.Length);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
File.Delete(FilePath);
}
You could use the following code to convert you text data to byte array
byte[] Data = File.ReadAllBytes(FilePath)
I won't recommended keeping generated files outside the web directory, even though its possible to write to a directory outside the web root in ASP.NET through impersonation, but its not at all recommended on production enviornment.
Probably d:\ is not a so good place. If you have a web server running on that server, you have to see where the Virtual Directory of the site in which you intend publish the file is located, and then put the file somewhere here.
When I have made files on the server, eg images I have saved to
Server.MapPath(#"~\" + sFilename)

Categories