i want a solution for this , i want to delete a file which is residing in my desk top using asp.net c# , i used below code:
try
{
FileInfo TheFile = new FileInfo(MapPath(".") + "\\" + FileNameTextBox.Text);
if (TheFile.Exists)
{
File.Delete(MapPath(".") + "\\" + FileNameTextBox.Text);
}
else
{
throw new FileNotFoundException();
}
}
catch (FileNotFoundException ex)
{
lblStatus.Text += ex.Message;
}
catch (Exception ex)
{
lblStatus.Text += ex.Message;
}
but it always says the file location cannot be found , please help me
thanks in advance `
If you are trying to delete a user's desktop file using an asp .net page you cannot do it. The code executes on the server side and the path will access to the desktop of the server that your application is being hosted.
I would try doing it this way instead:
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
File.Delete(Path.Combine(desktopPath, "filetobedeleted"));
Related
I am wondering on how to create a new directory for a log event file in windows service through c#
I have the following code:
public static void WriteLog(string Message)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\DataFile.txt", true);
//sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "C:\\MulpuriServiceLOG\\data.txt", true);
//sw.WriteLine(DateTime.Now.ToString() + ": " + Message);
sw.WriteLine(Message);
sw.Flush();
sw.Close();
}
catch{}
}
As the docuemtation states for the Directory.CreateDirectory(path):
Creates all directories and subdirectories in the specified path unless they already exist.
Modified from the example source code:
string path = #"c:\MyDir";
try
{
// Try to create the directory.
Directory.CreateDirectory(path);
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally {}
There is a really great tutorial on dotnetperls containing example code, exceptions, tips and other useful information about creating directories!
Look up that SO-question to create folders inside the same directory your executable has started, or simple use relative paths instead of absolute ones:
Directory.CreateDirectory("Test");
That way you will never have conflicts about finding the correct path!
File yourFolder= new File("C:/yourFolder");
// if the directory does not exist, create it
if (!yourFolder.exists()) {
System.out.println("Creando directorio: " + yourFolder.getName());
boolean result = false;
try
{
yourFolder.mkdir();
result = true;
}
catch(SecurityException se){
}
if(result) {
System.out.println("Folder created");
}
}
I am trying to delete files from isolated storage. But it returning error message to me. I don't know where i did mistake.
public void Delete(string folder, string fileName)
{
try
{
string path = folder + "\\" + fileName + ".txt";
string delPath = folder + "/" + fileName + ".txt";
MessageBox.Show(delPath);
if (myIsolatedStorage.DirectoryExists(folder))
{
if (myIsolatedStorage.FileExists(delPath))
{
myIsolatedStorage.DeleteFile(delPath);
MessageBox.Show("File is Deleted..!!");
}
else
MessageBox.Show("There is no file is exists");
}
else
{
MessageBox.Show("There is no Folder is exists");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Please let me know where i did mistake.
Thanks in advance..
Error message:-
Perhaps, the file, you're trying to delete, is still in usage. Your application should have no open files or references to files that you are trying to delete.
I have a simple program here wherein I can create a folder then save the an image to the folder created. The folder gets successfully created but I'm getting error into saving it to the newly created file. The error is:
The file could not be uploaded. The following error occured: 'N:/Kim's New Project/Safety Accident Report/File Uploader 2/File
Uploader 2/Uploads/asdsa' is a physical path, but a virtual path was
expected.
Can you please check my code. Please help. Thank you.
protected void button1_Click(object sender, EventArgs e)
{
if (FileUpload2.HasFile)
{
try
{
if (FileUpload2.PostedFile.ContentType == "image/jpeg")
{
if (FileUpload2.PostedFile.ContentLength < 512000)
{
string strpath = #"N:\Kim's New Project\Safety Accident Report\File Uploader 2\File Uploader 2\Uploads\" + txtName.Text;
if (!(Directory.Exists(strpath)))
{
Directory.CreateDirectory(strpath);
lblResult.Text = "Directory Created";
if ((Directory.Exists(strpath)))
{
string filename = Path.GetFileName(FileUpload2.FileName);
FileUpload2.SaveAs(Server.MapPath(strpath) + filename);
Label1.Text = "File uploaded successfully!";
}
}
else
{
lblResult.Text = "Already Directory Exists with the same name";
}
}
else
Label1.Text = "File maximum size is 500 Kb";
}
else
Label1.Text = "Only JPEG files are accepted!";
}
catch (Exception exc)
{
Label1.Text = "The file could not be uploaded. The following error occured: " + exc.Message;
}
}
Instead of
FileUpload2.SaveAs(Server.MapPath(strpath) + filename);
try
FileUpload2.SaveAs(Path.Combine(strPath, filename));
you already know the physical save path - no need for Server.MapPath
Try..
string strpath = Server.MapPath("~/Test");
if (!(Directory.Exists(strpath)))
{
Directory.CreateDirectory(strpath);
}
I am using two stored procedures, one for main report and another for subreport. Below is the code.
private void LoadSalesOrderReport()
{
string Type = gvQuotationDetails.Rows[QuoteIndex].Cells["Type"].EditedFormattedValue.ToString();
FilePath = ConfigurationManager.AppSettings["EMP_IMG_PATH"].ToString() + "\\" + ValQuoteID.ToString() + ".pdf";
DeleteExistingFile(FilePath);
try
{
AccountsPayableMaster objAPM = new AccountsPayableMaster();
QuotationReport obj = new QuotationReport();
objReportDocument.Load(Application.StartupPath + #"\rptQuotationReport.rpt");
obj.crysQuotationReport.LogOnInfo = objAPM.ConnectionDetails("SD_SalesOrderReport;1");
obj.crysQuotationReport.LogOnInfo = objAPM.ConnectionDetails("SD_GetBatchReportDetails;1");
obj.crysQuotationReport.ReportSource = objReportDocument;
objReportDocument.SetParameterValue("#QuoteID", ValQuoteID);
objReportDocument.SetParameterValue("Type", "-" + Type.ToUpper() + "-");
objReportDocument.SetParameterValue("#QuoteID", ValQuoteID, objReportDocument.Subreports[0].Name.ToString());
string[] Print = objAPM.GetPrintDetails();
SetPrintParameters(objReportDocument, Print);
obj.Show();
objReportDocument.ExportToDisk(ExportFormatType.PortableDocFormat, FilePath);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
OpenPdfFile();
}
private void OpenPdfFile()
{
try
{
Process.Start(FilePath);
}
catch (Exception ex)
{
MessageBox.Show("Please install MicrosoftOffice/Pdf Reader to view files", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
The code is working fine.But the problem is. when i click the button in front end to show the pdf directly.The crystal report form is also displayed and I know the reason as I am using obj.Show in my code.I tried to comment it but it throws an error.Can any one advise changes in my code to directly display the pdf and not the crystalreport form.
I like to open a new window in my project. I am using two panels in my project When I click the "Viewdocument" link in gridview(panel1) it should display the window to open that file. But in my code its not working can any one help me to solve this issue. Here is the code.
if (myReader.Read())
{
myReader.Close();
openWIndow("fr_OpenFile.aspx", "", fileName);
Linkbutton_ModalPopupExtender.Show();
//OpenMyFile();
}
else
{
myReader.Close();
Message("Cannot open selected file");
Linkbutton_ModalPopupExtender.Show();
return;
}
con.Close();
//OpenMyFile();
}
else
{
Message("File not found");
Linkbutton_ModalPopupExtender.Show();
}
}
catch (Exception ex)
{
lblmsg.Text = ex.Message;
}
}
private void openWIndow(String FileName, String WindowName, String qString)
{
String fileNQuery = FileName + "?value=" + qString;
String script = #"<script language=""javascript"">" + "window.open(" + fileNQuery + WindowName + "," + "menubar=Yes,toolbar=No,resizable=Yes,scrollbars=Yes,status=yes" + " );" + "</script>";
ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", script);
}
Thanks in Advance
There are many ways. You can do this by simply using target="_blank" in asp.net hyperlink control. You can do this using window.open() function in JavaScript. You can even register this JavaScript code from asp.net code behind. All detail is discussed here in How to open new window in asp.net, c# using JavaScript? Follow http://dotnetspidor.blogspot.com/2009/01/open-new-window-in-aspnet-web-page_28.html.
read this: http://www.velocityreviews.com/forums/t112713-open-new-browser-window-on-server-side-button-click.html