question

MarkusFreitag-0088 avatar image
0 Votes"
MarkusFreitag-0088 asked MarkusFreitag-0088 commented

C# Two applications can access the same XML file.

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


dotnet-csharp
overview-1.png (30.4 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

TimonYang-MSFT avatar image
1 Vote"
TimonYang-MSFT answered MarkusFreitag-0088 commented

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.


2.png (28.2 KiB)
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hello,
ok, but how does it work. When App1 has opened the file. The App2 also wants to open the file, the App2 should bring the message already open.

I want to create a WPF application. Load the file, visualize it. The loading process is now complete.
Should I somehow create an additional file to see that the file is already loaded?

A console application does not show the problem.

Line 10 Console.ReadLine(); // breakpoint.

Load the file with App2, is possible without error message.


Line 9 SaveDocument(document, fileName); // breakpoint
works, but that is not the real situation.

Any ideas? Thanks in advance.

0 Votes 0 ·
DuaneArnold-0443 avatar image
1 Vote"
DuaneArnold-0443 answered MarkusFreitag-0088 commented

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.

· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hello,
OK, can you make a simple sample?

Thanks in advance.

0 Votes 0 ·

Loading your Xml file as a FileStream, you could use the constructor that allows for a FileShare parameter. If you set this parameter to FileShare.None another user that trys to access the file while you're still at it receives a warning, that the file is in use.
XDocument doc = XDocument.Load(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None));

1 Vote 1 ·
 XDocument doc = XDocument.Load(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None));



Yes that is a good idea.
I load the file into my application, then I close it again. I don't leave this open all the time. I think that's the problem.


How can I best solve this? Which programming pattern is suitable?
I can't keep the file open all the time.

0 Votes 0 ·
DuaneArnold-0443 avatar image
0 Votes"
DuaneArnold-0443 answered

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.



5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.