C# 程序写入文本文件一次,但不会写入第二次

本文关键字:一次 第二次 文本 程序 文件 | 更新日期: 2023-09-27 18:32:20

我正在编写的程序用于注册设置。它可以很好地写入文本文件,但我想确保如果它没电并切断(平板电脑),它将保存文档。它第一次有效,但之后就没有工作了。

这是我的代码:

public void Form1_Load(object sender, EventArgs e)
{            
    this.TopMost = true;
    this.FormBorderStyle = FormBorderStyle.None;
    this.WindowState = FormWindowState.Maximized;
    textBox1.Select();
    var fileSave = new FileStream(fullFileName, FileMode.Create);
    fileSave.Close();
    //     DisableCloseButton(); 
}
private void textBox1_TextChanged_1(object sender, EventArgs e)
{
    // SqlConnection sqlConnection1 = new SqlConnection(
    //         "Data Source=DATABASE;Initial Catalog=imis;Integrated Security=True");
    //  SqlCommand cmd = new SqlCommand();
    Object returnValue;
    string txtend = textBox1.Text;
    try
    {
        string lastTwoChars = txtend.Substring(txtend.Length - 1);
        returnValue = textBox1.Text.Replace(@"*", "");
        if (lastTwoChars != "*") return;
        {
            if (listBox1.Items.Contains(returnValue))
            {
                for (int n = listBox1.Items.Count - 1; n >= 0; --n)
                {
                    string removelistitem = returnValue.ToString();
                    if (listBox1.Items[n].ToString().Contains(removelistitem))
                    {
                        //listBox1.Items.RemoveAt(n);
                    }
                }
            }
            else
                listBox1.Items.Add(returnValue);
            textBox1.Text = null;
            System.IO.StreamWriter sw = new System.IO.StreamWriter(fullFileName);
            foreach (object item in listBox1.Items)
                sw.WriteLine(item.ToString());
            sw.Close();
            if (listBox1.Items.Count != 0) 
            { 
                DisableCloseButton(); 
            }
            else
            {
                EnableCloseButton();
            }
            label6.Text = "Currently " + 
                 listBox1.Items.Count.ToString() + " in attendance.";
        }
    }
    catch { }
}

C# 程序写入文本文件一次,但不会写入第二次

使用 using 语句来确保释放所有资源。

取代

System.IO.StreamWriter sw = new System.IO.StreamWriter(fullFileName);
foreach (object item in listBox1.Items)
    sw.WriteLine(item.ToString());
sw.Close();

using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fullFileName))
{
    foreach (object item in listBox1.Items)
        sw.WriteLine(item.ToString());
}

您是否尝试过在关闭FileStream之前在上呼叫Stream.Flush()

我不知道

您触发问题的场景,但是这一行 如果 (lastTwoChars != "*") 返回;会跳过下面的逻辑,所以你写的可能永远不会被调用。附言您不会在关闭之前主动调用同花顺。

这是我代码中的工作示例,附加到文件中。

using (StreamWriter xyz = new StreamWriter(Path.Combine(File_Path, "xyz.txt"), true, Encoding.Unicode))
            {
                foreach (string item in listBox1.Items)
                {
                xyz.WriteLine("ABC"); // or whatever you want
                //xyz.WriteLine(item);
                xyz.Flush();
                }
            }

希望这有帮助。