简体   繁体   中英

How to read an xml file using xmldataprovider in wpf C#

I have a xaml file with my wpf controls defined, I am binding all its label controls to an xml file and populating from this file. I am doing using xmldataprovider using its source property

<Grid.DataContext>
<XmlDataProvider x:Name="LoadData" Source="data.xml" XPath="Loads/*" Document=/>
</Grid.DataContext>
<Label Grid.Row="1" Name="textbox1" Grid.Column="0" Grid.RowSpan="3" Grid.ColumnSpan="2" Background="Gray" BorderThickness="2" Content="{Binding XPath=teamname, Mode=OneWay}" FontSize="36">

and in the code behind,

 string filename = "C:\\data.xml";
            LoadData.Source = new Uri(filename);

Everything works fine, my only problem is i want to open this xml in read only mode as one of another program is writing to it and i get exception of" being used by another program"

is there any such provision from xmldataprovider to set the source/read the xml file in data provider..Has anyone does this before...input/suggestions are welcome...many thanks

There is no such possibility using the Source property. The Source represents an Uri based on which a WebRequest is created fetching the data using a Stream . You cannot control how this stream will be created though.

There is a workaround; however, you have to do that in code. You can manually load your XML document and assign it to the Document property of the XmlDataProvider .

Something like:

XmlDocument doc = new XmlDocument();
using (FileStream s = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    doc.Load(s);
}

LoadData.Document = doc;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM