C# Two applications can access the same XML file.

Markus Freitag 3,786 Reputation points
2021-04-01T14:08:17.827+00:00

Hello,
Two applications can access the same XML file.

A) I have opened the file in App1.
How can I prevent App2 from opening this file as well?
B) Or the other way around.
C) It should be possible that applications can access this file and change it in the Counter element. How can I solve this?
D) How do I know if the file is in progress?

E) How can I best implement a master detail ? UserInterface with WPF Desktop App?

Thanks for sample code how I can solve this task.
Priority is given to point A and B. This is the most important.

<PurchaseOrder PurchaseOrderNumber="99503" OrderDate="1999-10-20">  
      <Address Type="Shipping">  
        <Name>Ellen Adams</Name>  
        <Street>123 Maple Street</Street>  
        <City>Mill Valley</City>  
        <State>CA</State>  
        <Zip>10999</Zip>  
        <Country>USA</Country>  
      </Address>  
      <Address Type="Billing">  
        <Name>Tai Yee</Name>  
        <Street>8 Oak Avenue</Street>  
        <City>Old Town</City>  
        <State>PA</State>  
        <Zip>95819</Zip>  
        <Country>USA</Country>  
      </Address>  
      <DeliveryNotes>Please leave packages in shed by driveway.</DeliveryNotes>  
      <Items>  
        <Item PartNumber="872-AA">  
          <ProductName>Lawnmower</ProductName>  
          <Quantity>1</Quantity>  
          <USPrice>148.95</USPrice>  
          **<Counter>34</Counter>**  
          <Comment>Confirm this is electric</Comment>  
        </Item>  
        <Item PartNumber="926-AA">  
          <ProductName>Baby Monitor</ProductName>  
          <Quantity>2</Quantity>  
          <USPrice>39.98</USPrice>  
          **<Counter>234</Counter>**  
          <ShipDate>1999-05-21</ShipDate>  
        </Item>  
      </Items>  
    </PurchaseOrder>  

83678-overview-1.png

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,237 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Timon Yang-MSFT 9,571 Reputation points
    2021-04-02T05:13:50.433+00:00

    Try this code:

            static void Main(string[] args)  
            {  
                string fileName = @"D:\test\xml\2.xml";  
                XmlDocument document = LoadDocument(fileName);  
                  
                XmlNodeList nodes = document.SelectNodes("//Items//Item");  
                XmlNode node = nodes[0].SelectSingleNode("//Quantity");  
                node.InnerText = "3";  
                SaveDocument(document, fileName);  
                Console.ReadLine();  
            }  
            public static XmlDocument LoadDocument(String path)  
            {  
                XmlDocument document = new XmlDocument();  
                using (StreamReader stream = new StreamReader(path))  
                {  
                    document.Load(stream);  
                }  
                return (document);  
            }  
      
            public static XmlDocument SaveDocument(XmlDocument document, String path)  
            {  
                using (StreamWriter stream = new StreamWriter(path))  
                {  
                    document.Save(stream);  
                }  
                return (document);  
            }  
    

    It cannot prevent two programs from accessing the same program. After all, if App1's operation on this file has ended, then there is no reason to prevent App2 from operating this file.

    But it can report an exception when App2 tries to modify the file before App1 finishes modifying the file.

    For example, you can add a breakpoint on line 26 of the above code, run the project, and then run another project that accesses this file, you will see:

    83924-2.png

    You can catch this exception and deal with it to achieve your needs.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

  2. Duane Arnold 3,211 Reputation points
    2021-04-02T05:36:56.78+00:00

    If one program already has the text file open, because XML is text, then a second program trying to open the same text file while the first program has it opened is going to throw an exception stating that the file is already in use.

    It's that simple.

    1 person found this answer helpful.

  3. Duane Arnold 3,211 Reputation points
    2021-04-05T12:59:56.067+00:00

    I feel this is something that you can make a little program open a text file and then try to open the same text file again while you never closed the text file from the first opening of the file. You'll see the exception being thrown.

    Use notepad and make a text file, do the above and watch the progem blowup, because the file is open and the program tries to open it again. The only file that I know of that can be open concurrently is a database file attached to the DB engine such as MS SQL Server or other such DB server software. No flat file that I know about can be used concurrently and a XML file fits into that category.

    0 comments No comments