首页 > 开发 > 综合 > 正文

c#中对文件的操作小结

2024-07-21 02:20:13
字体:
来源:转载
供稿:网友
1、建立一个文本文件
public class fileclass
{
    public static void main()
    {
    writetofile();
    }
    static void writetofile()
    {
    streamwriter sw;
    sw=file.createtext("c:/mytextfile.txt");
    sw.writeline("god is greatest of them all");
    sw.writeline("this is second line");
    sw.close();
    console.writeline("file created sucacessfully");
    }
}

2、读文件
public class fileclass
{
    public static void main()
    {
    readfromfile("c:/mytextfile.txt");
    }
    static void readfromfile(string filename)
    {
    streamreader sr;
    string s;
    sr=file.opentext(filename);
    s=sr.readline();
    while(s!=null)
    {
    console.writeline(s);
    s=sr.readline();
    }
    sr.close();
    }
}

3、追加操作

public class fileclass
{
    public static void main()
    {
    appendtofile();
    }
    static void appendtofile()
    {
    streamwriter sw;
    sw=file.appendtext("c:/mytextfile.txt");
    sw.writeline("this line is appended");
    sw.close();
    console.writeline("text appended successfully");
    }
}



发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表