为什么StreamWriter不写入我的.txt文件? [英] Why doesn't StreamWriter write to my .txt file?

查看:77
本文介绍了为什么StreamWriter不写入我的.txt文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。我从来没有要求任何东西,这很简单。

但我无法以某种方式使它工作。



Hello. I never asked for anything, and this is pretty simple.
But I can't get it working somehow.

private void keyPress(object sender, KeyPressEventArgs e)
        {
            StreamWriter sw = new StreamWriter(@"C:\Users\Public\Documents\Test.txt");
            switch (e.KeyChar)
            {
                case 'a':
                    sw.Write("a");
                    sw.Flush();
                    return;
            }
        }





我打赌有人知道如何让sw写入我的.txt我按下'a'键。



谢谢,XauS。



I bet someone knows how to get the sw to write into my .txt when ever i press the key 'a'.

Thanks, XauS.

推荐答案

我的朋友。因为Stream是一次性的。你必须在操作它们后关闭它们。

这段代码对我有效:

Hi my friend. Because Stream is disposable. you must Close them after manipulate them.
this code works for me correctly:
switch (e.KeyChar)
            {
                case'a':
                    stream.Write(e.KeyChar);
                    stream.Close();
                    break;
            }



另一个重要的事情是在这里使用return。为什么?告诉我。

之后你必须使用休息。

祝你好运。


another important thing is using return here. why? tell me.
after case you must use break.
good luck.


试试这个代码,



Try this code,

private void keyPress(object sender, KeyPressEventArgs e)
        {
            try
            {

            StreamWriter sw = new StreamWriter
                           (@"C:\Users\Public\Documents\Test.txt");
            switch (e.KeyChar)
            {
                case 'a':
                    { // you haven't put this braces
                    sw.Write("a");
                    sw.Flush();
                    sw.close();
                    };
                    break; //you put return
            }
            }
           catch(Exception e)
           {
              //catch statements
           }
        }


使用此代码将文本写入文本文件



private void keyPress(object sender,KeyPressEventArgs e)

{

// StreamWriter sw = new StreamWriter(@" D: \ Test.txt");

开关(e.KeyChar)

{

案例'a':

File.AppendAllText(@" C:\Users\Public\Documents\Test.txt"," a");



return ;

}

}
use this code to write text into text file

private void keyPress(object sender, KeyPressEventArgs e)
{
//StreamWriter sw = new StreamWriter(@"D:\Test.txt");
switch (e.KeyChar)
{
case 'a':
File.AppendAllText(@"C:\Users\Public\Documents\Test.txt", "a");

return;
}
}


这篇关于为什么StreamWriter不写入我的.txt文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆