相关疑难解决方法(0)

如果文件不存在则创建文件

我需要让我的代码读取文件是否存在创建else附加.现在它正在读取它是否确实存在创建和追加.这是代码:

if (File.Exists(path))
{
    using (StreamWriter sw = File.CreateText(path))
    {
Run Code Online (Sandbox Code Playgroud)

我会这样做吗?

if (! File.Exists(path))
{
    using (StreamWriter sw = File.CreateText(path))
    {
Run Code Online (Sandbox Code Playgroud)

编辑:

string path = txtFilePath.Text;

if (!File.Exists(path))
{
    using (StreamWriter sw = File.CreateText(path))
    {
        foreach (var line in employeeList.Items)
        {
            sw.WriteLine(((Employee)line).FirstName);
            sw.WriteLine(((Employee)line).LastName);
            sw.WriteLine(((Employee)line).JobTitle);
        }
    }
}
else
{
    StreamWriter sw = File.AppendText(path);

    foreach (var line in employeeList.Items)
    {
        sw.WriteLine(((Employee)line).FirstName);
        sw.WriteLine(((Employee)line).LastName);
        sw.WriteLine(((Employee)line).JobTitle);
    }
    sw.Close();
}
Run Code Online (Sandbox Code Playgroud)

}

c# streamwriter

67
推荐指数
5
解决办法
18万
查看次数

在写之前删除所有以前的文本

我正在写一个文本文件,每次我写,我想清除文本文件.

try
{
    string fileName = "Profile//" + comboboxSelectProfile.SelectedItem.ToString() + ".txt";
    using (StreamWriter sw = new StreamWriter(("Default//DefaultProfile.txt").ToString(), true))
    {
        sw.WriteLine(fileName);
        MessageBox.Show("Default is set!");
    }
    DefaultFileName = "Default//DefaultProfile.txt";
}
catch 
{ 
}
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?我想从DefaultProfile.txt中删除所有以前的内容.

我实际上必须知道从文本文件中删除所有内容的方法或方法(只是一个名称).

stream streamwriter c#-4.0

12
推荐指数
3
解决办法
5万
查看次数

标签 统计

streamwriter ×2

c# ×1

c#-4.0 ×1

stream ×1