下面是我的代码。我的问题是根本没有创建file.txt!我找不到原因。程序应创建它。请你帮助我好吗 ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WriteToFile
{
class Program
{
static void Main(string[] args)
{
string line = "Please help me to write something!!";
System.IO.StreamWriter file = new System.IO.StreamWriter
(@"C:\Users\jgonc\source\repos\WriteToFile\WriteToFile\bin\Debug\file.txt");
file.Flush();
file.WriteLine(line);
file.Close();
Console.WriteLine("press a key");
Console.ReadKey();
}
}
}
//line you want to write to the document
string line = "Please help me to write something!!";
//path to my documents
string docPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter sw = new StreamWriter(Path.Combine(docPath, "test.txt")))
{
sw.WriteLine(line);
}
Console.WriteLine("press a key");
Console.ReadKey();
在这里,我使用了using关键字。这非常有用,因为在使用段结束时,在参数中创建的任何对象都将被自动销毁,这很棒,因为这意味着您不需要使用不必要的刷新和关闭来使代码混乱。
了解冲洗与关闭之间的区别也很重要。在使用段结束时,在streamwriter上调用dispose,然后依次调用close,从而关闭流。刷新只是清除缓冲区。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句