If XML Doesn't exist, Create one in order to a

2019-08-21 23:23发布

I want to check if my file does exist first, but if not.. How can i make it exist?

 if (File.Exists(Filepath))
 {

     // if it does exist, itll show datas as data grid view

     dataGridView2.DataSource = ds.Tables[0].DefaultView;

 }

 else
 {


     // if it doesnt exist, how can i make it exist? or create an XML file

 }

标签: c# asp.net
5条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-22 00:04

Use StreamWriter to create a new file, specify the path.

You can do this:

  using(var tw = new StreamWriter(path, true))
  {
      tw.WriteLine("New file content");
  }
查看更多
祖国的老花朵
3楼-- · 2019-08-22 00:07

You could use XmlDocument and XmlTextWriter

XmlDocument doc = new XmlDocument();
doc.LoadXml("<sample></sample>");  //your content here
// Save the document to a file
XmlTextWriter writer = new XmlTextWriter("sample.xml", null);
doc.Save(writer);
查看更多
贼婆χ
4楼-- · 2019-08-22 00:16

You could also just use a FileStream with the File class.

if (!File.Exists(Filepath))
{
    using (FileStream fs = File.Create(Filepath))
    {
        Byte[] info = new UTF8Encoding(true).GetBytes("Text in the file.");
        // Add some information to the file.
        fs.Write(info, 0, info.Length);
    }
}
查看更多
姐就是有狂的资本
5楼-- · 2019-08-22 00:16
using System.Xml.Linq; 

XDocument doc = new XDocument(
                         new XElement("YourNodeName")
                        );
doc.Save("your_doc_name.xml");
查看更多
走好不送
6楼-- · 2019-08-22 00:17

Another approach by using LINQ to XML types without explicit using of writers

if (File.Exists(Filepath))
{
    // do something
}
else
{
    var document =  
        new XDocument(new XElement("root", 
                                   new XElement("one", "value 1"),
                                   new XElement("two", "value 2"));

    document.Save(FilePath);
}
查看更多
登录 后发表回答