在使用C#编写文件时需要帮助 [英] Need help in writing on a file in c#

查看:105
本文介绍了在使用C#编写文件时需要帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须多次调用此函数

I have to call this function many times

        public void Insert(string name, string DT, int scope)
        {
            FileStream fHandler = new FileStream("c:\\SymbolTable.txt", FileMode.Append);
            fHandler.Close();
            StreamWriter sEntry = new StreamWriter("c:\\SymbolTable.txt");
            sEntry.WriteLine(name + "," + DT + "," + scope);
            sEntry.Close();
}



另一个类中的调用方法



calling method in another class

HelpingFunctions hF = new HelpingFunctions();
            hF.Insert("gh", "ggh", 0);
           hF.Insert("gh", "ggh", 1);



问题是我的文件只包含最后一个条目.



the problem is that my file only contains the last entry

推荐答案

好吧,是的.它只会是最后一个条目.
您将其打开以进行追加(使用fHandler),然后将其关闭,然后使用StreamWriter重新打开它-这会破坏任何现有内容.

将整个方法替换为:

Well, yes. It will be only the last entry.
You open it for append (using fHandler) then close that and re-open it with a StreamWriter - which destroys any existing content.

Replace your entire method with:

public void Insert(string name, string DT, int scope)
    {
    using (StreamWriter sw = File.AppendText("c:\\SymbolTable.txt"))
        {
        sw.WriteLine(name + "," + DT + "," + scope);
        }
    }


使用此方法:

use this one :

public void Insert(string name, string DT, int scope)
{
    //FileStream fHandler = new FileStream("d:\\SymbolTable.txt", FileMode.Append);
    //fHandler.Close();
    StreamWriter sEntry = new StreamWriter("d:\\SymbolTable.txt", true);
    sEntry.WriteLine(name + "," + DT + "," + scope);
    sEntry.Close();
}



对不起,我注释掉了前两行,但是如果要添加数据,我并没有达到目的.

希望对您有所帮助.



Excuse me that I commented out the first two lines but I didn''t get its purpose if you want to append data.

Hope it helps.


这篇关于在使用C#编写文件时需要帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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