IOException: The process cannot access the file 'filename' because it is being used by another process - asp.net

I have this code in my asp.net project:
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
using (StreamWriter sw = File.CreateText(Server.MapPath(#"~/AboutUs.txt")))
{
sw.Write(FreeTextBox1.Text);
sw.Close();
sw.Dispose();
lblError.Text = "تغییرات با موفقیت ذخیره شد.";
lblError.CssClass = "success";
}
}
catch (Exception ex)
{
lblError.Text = "خطایی روی داده است!" + "\n" + ex.ToString();
lblError.CssClass = "error";
}
finally
{
lblError.Visible = true;
}
}
Sometimes (not always) when I hit btnSave following error is occurred:
IOException: The process cannot access the file 'filename' because it is being used by another process
Why?

You just Run your application after see windows task manager-->Processes, any notepad.exe running you just right click then click end process . .

Related

Thread disrupting execution of ASP.net main application

I have an ASP.net web app that spawns a process (in a thread). This thread calls a '.dll' to connect to another 'subsystem'.
Problem is, when there are errors connecting to the 'subsystem', it affects my main application (main UI) and I get a 'connection refused message'. I have already put in 'try-catch' error handling routines in my thread. FYI, I would like to treat the thread as a 'Fire and forget' thread.
The thread is spawned when btnSubmit is clicked.
Please refer to trimmed-down extract of code.
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
txt_hide.Value = sStatus;
if (sStatus == "")
{
//create thread for posting
id = Guid.NewGuid();
Thread th = new Thread(() => postXMLClass.PostXML(sSeqNo));
th.Start();
sStatus = "Transaction generated..please check posting status..";
lblMessage.Text = "Transaction Generated...";
}
else
{
FormView1.DataBind(); //refresh the form
clib.Show2("Error generating transaction : " + sStatus, sender);
lblMessage.Text = "Error generating transaction : " + sStatus;
}
}
catch (SqlException ex)
{
lblMessage.Text = "Error generating transaction ...: " + ex.Message;
}
catch (Exception ex)
{
//sqc.Transaction.Rollback();
lblMessage.Text = "Error encountered...: " + ex.Message;
throw;
}
finally
{
if (dbc != null) dbc.Dispose();
if (clib != null) clib.Dispose();
}
}
public static void PostXML(string inlinkcode)
{
string sToken = "", sXMLOut = "";
Xml.Router.XMLRouter cX = new Xml.Router.XMLRouter();
try
{
cX.set_Options("com.xml.router.nameServer", appSetArray[0]);
cX.set_Options("com.xml.router.nameServerPort", appSetArray[2]);
cX.set_Options("com.xml.router.logicalServerName", appSetArray[1]);
{
sLinkcode = inlinkcode;
if (sLinkcode != null && sLinkcode != "")
{
strxml = "<?xml version=\"1.0\" encoding='UTF-8' ?>";
strxml += "<TableLinkRequest version=\"1.0\"><DocumentLinkStart><Request><StartParams>";
strxml += "<CmpCode>X</CmpCode><DocCode></DocCode></TableLinkRequest>";
sXMLOut = cX.Send(sToken, strxml);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception {0}", ex.Message);
}
finally
{
if (cX != null) cX.Logoff(sToken);
}
}

When calling CreateDocumentAsync(), do I need to check the ResourceResponse<Document> for errors?

When calling CreateDocumentAsync(), do I need to check the ResourceResponse for errors? For example, there is a .StatusCode property.
Or will try-catch handle all possible error conditions?
Try catch is the way,
try
{
//Get a Document client
using (client = new DocumentClient(new Uri(endpointUrl), authorizationKey))
{
RunDemoAsync(databaseId, CollectionId).Wait();
}
}
catch (DocumentClientException de)
{
Exception baseException = de.GetBaseException();
Console.WriteLine("{0} error occurred: {1}, Message: {2}", de.StatusCode, de.Message, baseException.Message);
}
catch (Exception e)
{
Exception baseException = e.GetBaseException();
Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
}
finally
{
Console.WriteLine("End of demo, press any key to exit.");
Console.ReadKey();
}

Null reference error when calling a method

I have a method called NewBatch_GetAndSetBatchID.
When I call this methode in the Page_Load methode it works perfectly.
But when I call this methode from a button (on the same page), I get:
Null reference exeption Object reference not set to an instance of an object.
It throws an error at:
BatchNoTextBox.Text = (batchID += 1).ToString();
When I debug, I can see that my batchID is filled with a value.
This is my code:
public void NewBatch_GetAndSetBatchID()
{
FormView1.ChangeMode(FormViewMode.Insert);
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand sqlCommando = new SqlCommand("SELECT MAX(BatchNo) FROM BM_BrewBatchHeader", conn);
try
{
conn.Open();
batchID = Convert.ToInt32(sqlCommando.ExecuteScalar());
}
catch (Exception)
{
}
finally
{
conn.Close();
}
}
}
catch (SqlException error)
{
}
try
{
TextBox BatchNoTextBox = (TextBox)FormView1.FindControl("BatchNoTextBox");
BatchNoTextBox.Text = (batchID += 1).ToString();
}
catch (Exception)
{
throw;
}
}
What can be the problem here?
I found the solution on another forum:
I have to use the PreRender trigger from the FormView. With the code below it works fine. When I now set the Formview to insert or edit mode the code executes perfectly.
protected void FormView1_PreRender(object sender, EventArgs e)
{
// if the mode is Edit or Insert
if (this.FormView1.CurrentMode == FormViewMode.Edit || this.FormView1.CurrentMode == FormViewMode.Insert)
{
TextBox BatchNoTextBox = (TextBox)FormView1.FindControl("BatchNoTextBox");
BatchNoTextBox.Text = (batchID += 1).ToString();
}
}

How to get pathname of image from FileUpload in grid view

Hello i have my FileUpload in gridview.I upload image for every row and then click button called UPLOAD. So that it should get image path from every row and upload. Onclick listener for UPLOAD is UploadBtn_onClick.
Code for UploadBtn_onClick is
protected void UploadBtn_onClick(object sender, EventArgs e)
{
foreach (GridViewRow row in StudentGrid.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
try
{
UpdateEmailProperties objUpdateEmailId = new UpdateEmailProperties();
GridViewRow grdrow = (GridViewRow)((FileUpload)sender).NamingContainer;
FileUpload filename = (FileUpload)grdrow.Cells[5].FindControl("fileuploadimages");
objUpdateEmailId.StudId = int.Parse(row.Cells[6].Text);
objUpdateEmailId.Email = row.Cells[3].Text;
objUpdateEmailId.profilepath = "profilepics/" + filename;
int intStatus;
intStatus = Stud.UpdateStudentEmailId(objUpdateEmailId);
if (intStatus != 0)
{
lblWarning.Text = "Updated successfully";
}
else
{
lblWarning.Text = "Failed to Update";
}
}
catch (Exception ex)
{
//LogFile.CreateLog("User", "AddPlacement", ex.Message);
lblWarning.Text = "Error: " + ex.Message.ToString();
}
}
}
}
But i am getting error as
Unable to cast object of type 'System.Web.UI.WebControls.Button' to type 'System.Web.UI.WebControls.FileUpload'
.
I need to fetch name of file returned from loadfile

Why is File.exists (Filename) statement not working?

This is my code
protected void btnAdd_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
switch(SubDrpDownList.SelectedIndex)
{
case 0:
if (!File.Exists(filename))
FileUploadControl.SaveAs(Server.MapPath("~/Books/Math/") + filename);
else if (File.Exists(filename))
{
throw new DuplicateWaitObjectException();
}
break;
case 1:
if (!File.Exists(filename))
FileUploadControl.SaveAs(Server.MapPath("~/Books/Physics/") + filename);
else if (File.Exists(filename))
{
throw new DuplicateWaitObjectException();
}
break;
case 2:
if (!File.Exists(filename))
FileUploadControl.SaveAs(Server.MapPath("~/Books/Drawing/") + filename);
else if (File.Exists(filename))
{
throw new DuplicateWaitObjectException();
}
break;
}
lblStatus.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
lblStatus.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
According to the category, I want books to be uploaded on diffrenet folder which i have achieved using switch statement. Problem is when i upload a book and then for the second time again upload it , File.Exists(filename) doesn't work. What I want is If i upload the same file twice, I want to throw an exception that duplicate file has been trying to be uploaded. But in case of case statement only line !File.Exists(filename)) gets executed even in case of duplicate file. Why is File.Exists(filename)) not getting executed??
The issue is that you are checking to see if the file exists based solely off of the filename, and not off of the full path to the file. What it should be is
protected void btnAdd_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
switch(SubDrpDownList.SelectedIndex)
{
case 0:
if (!File.Exists(Server.MapPath("~/Books/Math/") + filename))
FileUploadControl.SaveAs(Server.MapPath("~/Books/Math/") + filename);
else
{
throw new DuplicateWaitObjectException();
}
break;
case 1:
if (!File.Exists(Server.MapPath("~/Books/Physics/") + filename))
FileUploadControl.SaveAs(Server.MapPath("~/Books/Physics/") + filename);
else
{
throw new DuplicateWaitObjectException();
}
break;
case 2:
if (!File.Exists(Server.MapPath("~/Books/Drawing/") + filename))
FileUploadControl.SaveAs(Server.MapPath("~/Books/Drawing/") + filename);
else
{
throw new DuplicateWaitObjectException();
}
break;
}
lblStatus.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
lblStatus.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
This will account for the fact that where you are uploading the file is different than where you are checking the file exists
Also, the elseif just needs to be else, because it either exists or it doesn't so you don't need to check again that it exists, that is implied by the "else"
I think the problem you have is that you are reducing the full file name (with path) to just the file name here:
string filename = Path.GetFileName(FileUploadControl.FileName);
From that point !File.Exists is always true.
eg. you are reducing "C:\Somepath\myfile.txt" to "myfile.txt" then checking if it exists.

Resources