Accidentally Creating More Than One Process

Ice794

New Member
I am new to web programming (C# in Visual Web Developer) and my non-C programming skills are a little rusty too.I have created a table where some of the cells prompt for user input and, once the input is given, the input replaces the prompt. Thus the table can only be annotated by the first person to access the page. Later the annotated page needs to be made available for others to view it so I need the page to load without the prompts after they have been done for the first time. To do this I am (trying) to identify the user so that that person gets the editable page, all of the edits are saved to an xml file, and if another user runs the page the table settings get read back out of the xml file of edits.I am having trouble consistently writing to the xml file. Specifically I seem to sometimes create more than one process that is accessing the file and I throw a runtime exception when my code tries to update it.Since I didn't want a new file being created on each page load I thought a static class was the way to go. Here is the code:\[code\]static class XMLReaderWriter{ static String fileLocation = "D:\\WebApp\\dashboard.xml"; static XMLReaderWriter() { FileStream fs = File.Create(fileLocation); if (File.Exists(fileLocation)) { // The opening tag writeToFile(fileLocation, "<Dashboard>\n"); } else { Exception e = new Exception("Failed to create " + fileLocation); throw e; } } public static void writeXML(String xml) { if(File.Exists(fileLocation)) { writeToFile(fileLocation, xml); } else { File.Create(fileLocation); writeToFile(fileLocation, xml); } } private static void writeToFile(String fileLocation, String xml) { StreamWriter sw = new StreamWriter(fileLocation, true); sw.WriteLine(xml); sw.Close(); sw.Dispose(); } public static string readXML(String trendID) { StringBuilder result = new StringBuilder(""); if (File.Exists(fileLocation)) { XDocument xDoc = XDocument.Load(fileLocation); var image = from id in xDoc.Descendants(trendID) select new { source = id.Attribute("image").Value }; foreach (var imageSource in image) { result.AppendLine(imageSource.source); } } return result.ToString(); } public static void done() { // The closing tag writeToFile(fileLocation, "</Dashboard>"); }}\[/code\]and here is where I am calling the methods:\[code\]XMLReaderWriter.writeXML("\t<trend id=\"" + trendID +"\">\n\t\t" + innerHTML + "\" />\n\t</trend>");\[/code\]and finally there is a submit button to add the closing tag to the xml file:\[code\]<asp:Button runat="server" Text="Submit Changes" OnClick="Submit_Click" />protected void Submit_Click(Object sender, EventArgs e){ XMLReaderWriter.done();}\[/code\]Sometimes everything works just fine -- although I seem to be producing malformed xml. But most of the time I get more than one process accessing the xml file.Any advice is appreciated.Regards.
 
Back
Top