Chddz
Chddz

Reputation: 15

How to create file with a written data inside C# ASP.NET

 var myFile = File.Create("sample.xml");

//insert root element here
//or something like this                           
//<?xml version="1.0"?>
//< Information xmlns:xsd="http://www.w3.org/2001/XMLSchema" //xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>


myFile.Close();

cause, if the system cant locate the "sample.xml" it will create a new sample.xml.. But its empty. I want it to create a new sample.xml with root element inside, how can i do it?

Upvotes: 0

Views: 82

Answers (1)

Souvik Ghosh
Souvik Ghosh

Reputation: 4616

An XML file would be something like this-

<breakfast_menu>
    <food>
        <name>Belgian Waffles</name>
        <price>$5.95</price>
        <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
    </food>
    <food>
        <name>Strawberry Belgian Waffles</name>
        <price>$7.95</price>
        <description>Light Belgian waffles covered with strawberries and whipped cream</description>
    </food>
</breakfast_menu>

Now you can similarly take this content and write to a file.

string xmlContent = @"<breakfast_menu>
    <food>
        <name>Belgian Waffles</name>
        <price>$5.95</price>
        <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
    </food>
    <food>
        <name>Strawberry Belgian Waffles</name>
        <price>$7.95</price>
        <description>Light Belgian waffles covered with strawberries and whipped cream</description>
    </food>
</breakfast_menu>";

string path = @"C:\Souvik\Test.xml";

File.WriteAllText(path, xmlContent);

The File.WriteAllText will create a new file or overwrite an existing file.

Upvotes: 1

Related Questions