我想检查我的文件是否确实存在,但如果不存在..我怎么能让它存在?
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
}
答案 0 :(得分:0)
使用StreamWriter创建新文件,指定路径。
你可以这样做:
using(var tw = new StreamWriter(path, true))
{
tw.WriteLine("New file content");
}
答案 1 :(得分:0)
您可以使用XmlDocument
和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);
答案 2 :(得分:0)
您也可以FileStream
使用File
类。
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);
}
}
答案 3 :(得分:0)
使用LINQ to XML类型而不明确使用编写器的另一种方法
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);
}
答案 4 :(得分:0)
using System.Xml.Linq;
XDocument doc = new XDocument(
new XElement("YourNodeName")
);
doc.Save("your_doc_name.xml");