[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1775
  • Last Modified:

xml file in use by another process error

How do I resolve this problem?

I have a poll that writes to an XML file. I get the following error when multiple users access the poll and try to write to the XML file.

Server Error in '/' Application.
--------------------------------------------------------------------------------

The process cannot access the file 'F:\votes.xml' because it is being used by another process.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.IOException: The process cannot access the file 'F:\votes.xml' because it is being used by another process.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace:

[IOException: The process cannot access the file 'F:\votes.xml' because it is being used by another process.]
   System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +2015277
   System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) +998
   System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) +114
   System.Xml.XmlTextWriter..ctor(String filename, Encoding encoding) +38
   System.Data.DataSet.WriteXml(String fileName, XmlWriteMode mode) +73
   System.Data.DataSet.WriteXml(String fileName) +6
   polls.WebForm1.Button1_Click(Object sender, EventArgs e) in c:\inetpub\poll\default.aspx.cs:171
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5102
0
fwsteal
Asked:
fwsteal
  • 5
  • 2
1 Solution
 
orbulatCommented:
you can write the xml to another file name, a.xml --> a_1234.xml
or write a function for writing the xml file, it's looping until the file is accessible
here is the example

http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/ASP_DOT_NET/Q_20991782.html
0
 
sukumar_diyaCommented:
Hi,

If you are using xml reader, check whether you are closing the xmlerader. If t he xmlreader is not closed it will give this error.

Hope this helps you,
Suk
0
 
fwstealAuthor Commented:
I want to keep the same xml file as I want to keep all the vote casts to one xml file. I do two things with this xml file: 1. write/append to it; 2. read the file after writing or if the user has already written to the file read it onload.

Is  there a way to free up the xml after a read or write so that it can be free and available to all users?
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
fwstealAuthor Commented:
how do I check if the reader is closed or the write is closed? I'm using c# 1.1
0
 
sukumar_diyaCommented:
hi,
Check whether you r closing the reader or writer u r using to read the xml file.

ex:
XmlReader xreader;
// Code to load xml and read the values
//finally close the reader
xreader.close();

XmlWriter w = new XmlTextWriter(@"c:\test.xml", Encoding.UTF8);
// code to write content
//finally close the writer
w.close();

Suku
0
 
fwstealAuthor Commented:
here is a copy of my page load:

private void Page_Load(object sender, System.EventArgs e)
            {
                  //check to see if the user's ip address is currently in the xml file, if so then disable the vote button
                  string strIP = Request.ServerVariables["REMOTE_ADDR"].ToString();
                  //1st time page loads, determine if xml is present and determine if ip is present in xml file
                  if (!IsPostBack )
                        {
                              //does xml exist?
                              if (File.Exists(Server.MapPath("votes.xml"))==true )
                                    {
                                          //xml file found so render contents
                                          getrec();
                                          //check to see if ip is present in xml file, if it is disable voting to prevent multi ip voting
                                          ds=new DataSet();
                                          ds.ReadXml(Server.MapPath("votes.xml"));
                                          //find the ip using rowfilter
                                          ds.Tables[0].DefaultView.RowFilter="ip='" + strIP + "'" ;
                                          DataView ldsvFind = ds.Tables[0].DefaultView;
                                          if (ldsvFind.Count >0)
                                                {
                                                      Button1.Enabled = false;
                                                      LabelVoteMessage.Visible = true;
                                                      LabelVoteMessage.Text = "Thanks for casting a vote.";
                                                }
                                    }
                        }
                  //page has been posted back to server
                  if (IsPostBack)
                  {
                        //version 1 - query xml to determine if the ip is present in the xml file
                        //2nd line of defense to protect from multi ip voting
                        if (File.Exists(Server.MapPath("votes.xml"))==true )
                        {
                              StreamReader sr = new StreamReader(Server.MapPath("votes.xml"));
                              String str = sr.ReadToEnd();
                              XmlDocument doc = new XmlDocument();
                              doc.LoadXml(str);
                              XmlNode root = doc.DocumentElement;
                              XmlNode vote;
                              for (int i=0; i<root.ChildNodes.Count; i++)
                              {
                                    vote = root.ChildNodes[i];
                                    if (vote["ip"].InnerText != "")
                                    {
                                          //ip was found so disable voting
                                          Button1.Enabled = false;
                                          LabelVoteMessage.Visible = true;
                                          LabelVoteMessage.Text = "Thanks for casting a vote.";
                                    }          
                              }
                              sr.Close();
                        }
                        else
                        {
                              //ip was not found
                              LabelVoteMessage.Visible = false;
                              LabelVoteMessage.Text = "";
                        }
                  }
            }

how do I close the read when I open the xml file into a dataset?
0
 
fwstealAuthor Commented:
here is my function - getrec:

public void getrec()
            {
                  //render contents of xml file to a dataset
                  ds=new DataSet();
                  ds.ReadXml( Server.MapPath("votes.xml"));
                  DataTable dt=ds.Tables[0];
                  DataView d =ds.Tables[0].DefaultView;
                  t1.Text ="Total votes = " + dt.Rows.Count;  
                  cnt=dt.Rows.Count;
           
                  ds.Tables[0].DefaultView.RowFilter="val='1'";
                  t2.Text=  "Total One = " +  ((100*  ds.Tables[0].DefaultView.Count)/cnt).ToString()+"%";
                  ds.Tables[0].DefaultView.RowFilter="";

                  ds.Tables[0].DefaultView.RowFilter="val='2'";
                  t3.Text="Total Two = " +  ((100*  ds.Tables[0].DefaultView.Count)/cnt).ToString()+"%";
                  ds.Tables[0].DefaultView.RowFilter="";

                  ds.Tables[0].DefaultView.RowFilter="val='3'";
                  t4.Text="Total Three = " +  ((100*  ds.Tables[0].DefaultView.Count)/cnt).ToString()+"%";
                  ds.Tables[0].DefaultView.RowFilter="";

                  ds.Tables[0].DefaultView.RowFilter="val='4'";
                  t5.Text="Total Four = " +  ((100*  ds.Tables[0].DefaultView.Count)/cnt).ToString()+"%";
                  ds.Tables[0].DefaultView.RowFilter="";

                  ds.Tables[0].DefaultView.RowFilter="val='5'";
                  t6.Text="Total Don't know = " + ((100*  ds.Tables[0].DefaultView.Count)/cnt).ToString()+"%";    
                  ds.Tables[0].DefaultView.RowFilter="";
            }
0
 
fwstealAuthor Commented:
here is my code for the vote button

            private void Button1_Click(object sender, System.EventArgs e)
            {
                  string st="";
                  string strIP = Request.ServerVariables["REMOTE_ADDR"].ToString();
                  //do the work
                  if (File.Exists(Server.MapPath("votes.xml"))==false )
                  {
                        //xml file not found so create it and write the contents of the 1st vote
                        StreamWriter  fs=new StreamWriter(Server.MapPath("votes.xml"),false);  
                        st="<?xml version='1.0'?><root><vote><val>" +vote.Items[vote.SelectedIndex].Value.ToString() + "</val>";
                        st+="<ip>" + strIP.ToString() + "</ip>";
                        st+="</vote></root>";
                        fs.Write(st);                               
                        fs.Close();
                        getrec();
                  }
                  else
                  {
                        //xml file was found so append to it
                        //check to see if ip is present
                        //if found disable voting and don't append to file
                        ds=new DataSet();
                        ds.ReadXml(Server.MapPath("votes.xml"));
                        //find the ip using rowfilter
                        ds.Tables[0].DefaultView.RowFilter="ip='" + strIP + "'" ;
                        DataView ldsvFind = ds.Tables[0].DefaultView;
                        if (ldsvFind.Count >0)
                        {
                              getrec();
                        }
                        else
                        {
                              //else append to xml file
                              ds=new DataSet();
                              ds.ReadXml(Server.MapPath("votes.xml"));
                              DataRow dr =ds.Tables[0].NewRow();
                              dr["val"] =vote.Items[vote.SelectedIndex].Value.ToString() ;
                              dr["ip"] = strIP.ToString();
                              ds.Tables[0].Rows.Add(dr);
                              ds.WriteXml(Server.MapPath("votes.xml"));
                              getrec();
                        }
                  }            
                  //disable voting after clicking vote button
                  Button1.Enabled = false;
                  LabelVoteMessage.Visible = true;
                  LabelVoteMessage.Text = "Thanks for casting a vote.";
            }
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 5
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now