Displaying random XML file in DataGrid - c#

I have been following this article to read an XML file into a datagridview control.
I am posting the relevant piece of code here.
string filePath = "Complete path where you saved the XML file";
dsAuthors.ReadXml(filePath);
dataGrid1.DataSource = dsAuthors;
dataGrid1.DataMember = "authors";
dataGrid1.CaptionText = dataGrid1.DataMember;
Now I want to be able to read any XML file without knowing the elements of the XML file, but the above method requires me to declare the dataGrid1.DataMember = "authors"; which in case of random XML file, I will not know.
Thanks,
Abijeet.

With a little luck the following property has been filled:
dataGrid1.DataMember = dsAuthors.Tables[0].Tablename;

Related

Open a file without dialog

with openFileDialog you would select a file and after pressing "OPEN" it would paste the filepath of the selected file (c:\blob\template) into an textbox.
I would like to do automatically select the file c:\blob\template en then put the filepath in the textbox. basically the exact same thing as openfiledialog without a dialog. i have been trying to do this for some time now. can somebody help me out with this? i have no clue how to realise this.
i`m only able to get the filepath and paste the string in the textbox but this but only fills the box with a string. i need to load the file/template in there.
private void txt()
{
string fileName = "template";
string fullPath;
fullPath = Path.GetFullPath(fileName);
lblFirstTemplate.Text = fullPath;
}
Thank you in advance!
The code you now have will only get the file path. What you need to add is code that will actually open the file and read its content.
Let's say your file contains some text. You can use the following line to read the complete file as text:
System.IO.File.ReadAllText(fullPath);
If your file contains some other data like binary data, you can use:
System.IO.File.ReadAllBytes(fullPath);
And instead of reading all data at once, you can read it one line or a couple of bytes at a time. A good place in the documentation to start is: Common I/O Tasks

how to edit utf-16 xml file if it have string line after the end of the main Node

I have Special XML file with utf-16 encoding type. this file used to store data and I need to Edit it Using C# windows forms Application
<?xml version="1.0" encoding="utf-16"?>
<cProgram xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" ID="b0eb0c7e-f4de-4bc7-9e62-7a086a8c2fn8" Version="16.01" xmlns="cProgram">
<Serie>N </Serie>
<No>123456</No>
<type>101</type>
<Dataset4>larg data here 2 million char</Dataset4>
</cProgram>123456FF896631N 4873821012013-06-14
the problem is: it is not ordinary XML file
Because at the very End of the file I have a string line too, and that would give this error
Data at the root level is invalid. Line x, position x
when I try to load it as xml file
I tried to temporary replace the last line and get it back after I change the inner text, and it works But I lost the declaration Line and I didn't find a way to rewrite it when I have that text at the end of the file !_
so I need to change the InnerText of (Serie) and (No) nodes
but I don't Want to lose the declaration Line or the string text at the end of the file
try this piece of code:
string line = "";
string[] stringsperate = new string[] { "</cProgram>" };
using (StreamReader sr = new StreamReader("C://blah.xml"))
{
line = sr.ReadToEnd();
Console.WriteLine(line);
}
string text = line.Split(stringsperate, StringSplitOptions.None)[0];
text += "</cProgram>";
XmlDocument xd = new XmlDocument();
xd.LoadXml(text);
Console.Read();
Hope this helps
XDocument.Save() should persist the XML declaration line if the declaration exists initially. I also checked with your XML and the declaration line saved as expected :
var xml = #"<?xml version=""1.0"" encoding=""utf-16""?>
<cProgram xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" ID=""b0eb0c7e-f4de-4bc7-9e62-7a086a8c2fn8"" Version=""16.01"" xmlns=""cProgram"">
<Serie>N </Serie>
<No>123456</No>
<type>101</type>
<Dataset4>larg data here 2 million char</Dataset4>
</cProgram>";
var doc = XDocument.Parse(xml);
doc.Save("test.xml");
So you can implement your idea to temporarily replacing the last line and get it back after changing the inner text.
Fyi, XDocument's .ToString() method doesn't write XML declaration line, but .Save() method does. Question related to this : How to print <?xml version="1.0"?> using XDocument
allow me to answer my question
when I used doc.Load(filepath); it always give Error cause of the disturbing last Line
and C# use UTF-8 as defaults to work with xml files.But in this question it is UTF-16
So I found a very short way to do this & replace innertext with string as I want
string text = File.ReadAllText(filepath);
text = text.Replace("<Serie>N", "<Serie>"+textBox1.Text);
text = text.Replace("<Nom>487382","<Nom>"+textBox2.Text);
//saving file with UTF-16
File.WriteAllText("new.xml", text , Encoding.Unicode);
Question related to this [blog]: How to save this string into XML file? "it is much more answer related than being Question related"

Convert .txt to .xml

I am looking for a way in C# to input a text file and output an xml. After some searching, I have found ways to input strings and output as xml, and by hand input some text into a C# source code, and output as xml, but not to import a text file and output. I need this as I have an application that saves some computer-specific info to a txt file. I would like to make a C# program that takes this .txt and outputs it as .xml . All .txt files will have the same format. If possible I would like it to output to something like:
<Data>
<Info>#</Info>
All the contents of the text file would output into the # area. Thank you for the help!
Assuming you need to add xml element for every line in txt, you can write similar to following (XLINQ).
String[] data = File.ReadAllLines("TextFile.txt");
XElement root = new XElement("root",
from item in data
select new XElement("Line",item));
root.Save("XmlFile.Xml");
Output
<root>
<Line>Hello</Line>
<Line>World</Line>
</root>
The following will open a file, read the contents, create a new XML document, and then save the results to the same path as the original, only with an XML extension.
var txt = string.Empty;
using (var stream = File.OpenText(pathToFile))
{
txt = stream.ReadToEnd();
}
var xml = new XDocument(
new XElement("Data",
new XElement("Info", txt)));
xml.Save(Path.ChangeExtension(pathToFile, ".xml"));

Copy one Xml Document contents into another one in C#

I am trying to copy contents of one xml file into another xml file. I found many examples where copying nodes is done but could not find how to just copy all the content.
Is this possible at all? If so can you please provide some direction.
Thanks
Edit:
I want to create this new xml file in the location dynamically supplied by the application's text box.
Thanks again.
If you want to replace one XML file with another, why not use File.Copy?
As a file:
string sourcefile = "somefile.xml";
string destinationfile = "anotherFile.xml";
System.IO.File.Copy(sourcefile, destinationfile);
Is File.Copy() what you're looking for?

Accessing the content of the file

//Introduction
Hey, Welcome.....
This is the tutorial
//EndIntro
//Help1
Select a Stock
To use this software you first need to select the stock. To do that, simply enter the stock symbol in the stock text-box (such as "MSFT").
To continue enter "MSFT" in the stock symbol box.
//EndHelp1
//Help2
Download Stock Data
Next step is to to download the stock data from the online servers. To start the process simply press the "Update" button or hit the <ENTER> key.
After stock data is downloaded the "Refresh" button will appear instead. Press it when you want to refresh the data with the latest quote.
To continue make sure you are online and press the "Update" button
//EndHelp2
First time I want to display the content between //Introduction and //EndIntro then second time the content between //Help1 and //EndHelp1 and so on.
That's a very open-ended question - what sort of file? To read binary data from it you'd usually use:
using (Stream stream = File.OpenRead(filename))
{
// Read from the stream here
}
or
byte[] data = File.ReadAllBytes(filename);
To read text you could use any of:
using (TextReader reader = File.OpenText(filename))
{
// Read from the reader
}
or
string text = File.ReadAllText(filename);
or
string[] lines = File.ReadAllLines(filename);
If you could give more details about the kind of file you want to read, we could help you with more specific advice.
EDIT: To display content from an RTF file, I suggest you load it as text (but be careful of the encoding - I don't know what encoding RTF files use) and then display it in a RichTextBox control by setting the Rtf property. Make the control read-only to avoid the user editing the control (although if the user does edit the control, that wouldn't alter the file anyway).
If you only want to display part of the file, I suggest you load the file, find the relevant bit of text, and use it appropriately with the Rtf property. If you load the whole file as a single string you can use IndexOf and Substring to find the relevant start/end markers and take the substring between them; if you read the file as multiple lines you can look for the individual lines as start/end markers and then concatenate the content between them.
(I also suggest that next time you ask a question, you include this sort of detail to start with rather than us having to tease it out of you.)
EDIT: As Mark pointed out in a comment, RTF files should have a header section. What you've shown isn't really an RTF file in the first place - it's just plain text. If you really want RTF, you could have a header section and then the individual sections. A better alternative would probably be to have separate files for each section - it would be cleaner that way.
Not sure I understand your question correctly. But you can read and write content using System.IO.StreamReader and StreamWriter classes
string content = string.Empty;
using (StreamReader sr = new StreamReader("C:\\sample.txt"))
{
content = sr.ReadToEnd();
}
using (StreamWriter sw = new StreamWriter("C:\\Sample1.txt"))
{
sw.Write(content);
}
Your question needs more clarification. Look at System.IO.File for many ways to read data.
The easiest way of reading a text file is probably this:
string[] lines = File.ReadAllLines("filename.txt");
Note that this automatically handles closing the file so no using statement is need.
If the file is large or you don't need all lines you might prefer to reading the text file in a streaming manner:
using (StreamReader streamReader = File.OpenText(path))
{
while (true)
{
string line = streamReader.ReadLine();
if (line == null)
{
break;
}
// Do something with line...
}
}
If the file contains XML data you might want to open it using an XML parser:
XDocument doc = XDocument.Load("input.xml");
var nodes = doc.Descendants();
There are many, many other ways to read data from a file. Could you be more specific about what the file contains and what information you need to read?
Update: To read an RTF file and display it:
richTextBox.Rtf = File.ReadAllText("input.rtf");

Categories