繁体   English   中英

C#创建txt文件并保存

[英]C# Create txt file and save

我正在尝试创建文件并保存文本,但是只有创建文件的人才能提出问题所在吗?

private void button2_Click(object sender, EventArgs e)
    {
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.Filter = "Text File|*.txt";
        sfd.FileName = "Password";
        sfd.Title = "Save Text File";
        if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            string path = sfd.FileName;
            StreamWriter bw = new StreamWriter(File.Create(path));
            bw.Write(randomstring);
            bw.Dispose();
        }
    }

您需要先调用bw.Close()然后再调用bw.Dispose() 根据API:“您必须调用Close来确保将所有数据正确写到基础流中。” http://msdn.microsoft.com/zh-cn/library/system.io.streamwriter.close(v=vs.110).aspx

我实际上将代码更改为:

using (StreamWriter bw = new StreamWriter(File.Create(path)))
{
    bw.Write(randomstring);
    bw.Close();
}

无论是否成功完成, using块都会自动调用Dispose()

尝试改用File.WriteAllText

    if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        //...
        File.WriteAllText(path, randomstring);
    }    
bw.Write(randomstring);
bw.Dispose();

您编写一些东西,然后完全处置该对象。 尝试:

bw.Write(randomstring);
bw.Close();
bw.Dispose();

根据文档 ,您需要在处理前调用bw.Close() 另外,您应该使用using确保所有IDisposable都得到正确处理。

if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    string path = sfd.FileName;
    using (var fs = File.Create(path))
    using (StreamWriter bw = new StreamWriter(fs))
    {
        bw.Write(randomstring);
        bw.Close();
    }
}

或者只使用File.WriteAllText

if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    string path = sfd.FileName;
    File.WriteAllText(path, randomstring);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM