将某些内容写入文件然后再次加载

时间:2014-04-16 01:31:59

标签: c#

好吧所以我想知道我将如何采取文本框中的内容,然后按下按钮,textBox的内容将保存到文件位置,然后当我加载.exe备份时,内容将重新出现在textBox中。

这是我到目前为止所拥有的

private void button3_Click(object sender, EventArgs e)
{
File.WriteAllText(@"C:\Application.txt", textBox1.Text);
}

^要将它写入文件位置,我已多次尝试过,但它似乎不想在我的C上创建文件:。

private void Form1_Load(object sender, EventArgs e)
{
try
{
textBox1.Text = File.ReadAllText(@"C:\Application.txt", Encoding.ASCII);
}
catch
{

}

^要加载文件,然后将其注入到来自

的文本框中

感谢所有帮助, 感谢。

3 个答案:

答案 0 :(得分:3)

尝试写入C驱动器时可能会出现异常,因为它需要管理访问权限。尝试以管理员身份运行Visual Studio(因此,当从VS开始时,应用程序将以管理员身份运行)或尝试写入其他位置。你的代码都很好。 Encoding.ASCII位是不必要的,我建议删除它(很可能不是你要写入文件的编码)。

答案 1 :(得分:1)

尝试直接写入C:驱动器可能会导致问题。

尝试写入您确实具有写入权限的位置。您可以使用ApplicationData目录(对于当前用户特有的应用程序文件),或者如果您愿意,可以使用SpecialFolder.MyDocuments

private string applicationFilePath = Path.Combine(Environment.GetFolderPath(
    Environment.SpecialFolder.ApplicationData), "Application.txt");

private void button3_Click(object sender, EventArgs e)
{
    File.WriteAllText(applicationFilePath, textBox1.Text);
}

private void Form1_Load(object sender, EventArgs e)
{
    textBox1.Text = File.ReadAllText(applicationFilePath, Encoding.ASCII);
}

答案 2 :(得分:0)

我会做这样的事情:

using System.IO;

private void button3_Click(object sender, EventArgs e)
{
    using (var stream = new FileStream(@"C:\Application.txt", FileMode.Create))
    using (var writer = new StreamWriter(stream, Encoding.ASCII))
        writer.Write(textBox1.Text);
}

private void Form1_Load(object sender, EventArgs e)
{
    using (var stream = new FileStream(@"C:\Application.txt", FileMode.Open))
    using (var reader = new StreamReader(stream, Encoding.ASCII))
        textBox1.Text = reader.ReadToEnd();
}

我认为这种方法可以让您更好地控制自己的内容。尝试浏览FileMode枚举的内容,并确保添加使用System.IO; 指令。
请注意不要将using statementusing directive混淆。

此外,请务必记住在完成后处理/关闭您的流,以确保数据已刷新,并且您的应用程序不再使用该文件。这里,using语句完成了当流不再使用时处理的工作。

编辑:正如其他帖子所提到的,由于Admininstrative Access限制,写入C:目录会导致较新的操作系统出现问题。确保写入您绝对可以访问的不同驱动器/文件夹。

// Current User
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Application.txt");
// All users
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Application.txt");