当前位置: 代码网 > it编程>编程语言>Asp.net > C#读取与写入txt文件内容的实现方法

C#读取与写入txt文件内容的实现方法

2024年08月12日 Asp.net 我要评论
一、读取txt文件内容1.1 使用streamreaderusing system;using system.io; class program{ static void main() {

一、读取txt文件内容

1.1 使用 streamreader

using system;
using system.io;
 
class program
{
    static void main()
    {
        string filepath = @"c:\path\to\your\file.txt";
        
        try
        {
            using (streamreader reader = new streamreader(filepath))
            {
                string line;
                while ((line = reader.readline()) != null)
                {
                    console.writeline(line);
                }
            }
        }
        catch (filenotfoundexception)
        {
            console.writeline("文件未找到,请检查文件路径是否正确。");
        }
        catch (ioexception e)
        {
            console.writeline("读取文件时发生错误: " + e.message);
        }
    }
}

1.2 使用 file.readalllines

using system;
using system.io;
 
class program
{
    static void main()
    {
        string filepath = @"c:\path\to\your\file.txt";
        
        try
        {
            string[] lines = file.readalllines(filepath);
            foreach (string line in lines)
            {
                console.writeline(line);
            }
        }
        catch (filenotfoundexception)
        {
            console.writeline("文件未找到,请检查文件路径是否正确。");
        }
        catch (ioexception e)
        {
            console.writeline("读取文件时发生错误: " + e.message);
        }
    }
}

1.3 使用 file.readalltext

using system;
using system.io;
 
class program
{
    static void main()
    {
        string filepath = @"c:\path\to\your\file.txt";
 
        try
        {
            // 读取整个文件到一个字符串变量
            string content = file.readalltext(filepath);
 
            // 打印文件内容
            console.writeline(content);
        }
        catch (filenotfoundexception)
        {
            console.writeline("文件未找到,请检查文件路径是否正确。");
        }
        catch (ioexception e)
        {
            console.writeline("读取文件时发生错误: " + e.message);
        }
    }
}

1.4 注意点

在写入文件之前,务必检查文件和目录是否存在,以避免不必要的错误。使用 try-catch 块来捕获并处理任何可能发生的异常,这是一个良好的编程实践。

二、写入txt文件内容

2.1 追加内容到文本文件

using system;
using system.io;
 
class program
{
    static void main()
    {
        string filepath = @"c:\path\to\your\file.txt";
        string contenttoappend = "新添加的一行内容。\n";
        
        try
        {
            file.appendalltext(filepath, contenttoappend);
            console.writeline("内容已追加到文件。");
        }
        catch (ioexception e)
        {
            console.writeline("写入文件时发生错误: " + e.message);
        }
    }
}

2.2 覆盖内容到文本文件

using system;
using system.io;
 
class program
{
    static void main()
    {
        string filepath = @"c:\path\to\your\file.txt";
        string contenttowrite = "这是新的文件内容。\n";
        
        try
        {
            file.writealltext(filepath, contenttowrite);
            console.writeline("文件内容已更新。");
        }
        catch (ioexception e)
        {
            console.writeline("写入文件时发生错误: " + e.message);
        }
    }
}

2.3 注意点

在上述两个示例中,如果指定的文件路径不存在,file.writealltext和file.appendalltext方法会创建一个新文件,并分别覆盖或追加内容。如果文件已经存在,它们会相应地写入或追加内容。

需要注意的是,这些方法会在没有提示的情况下覆盖现有文件的内容(file.writealltext),所以在使用时要小心,确保你了解这些操作的影响。

三、c++ 写入txt文件内容并追加内容

可以使用ofstream类来写入txt文件内容。若想追加内容,可以使用ios::app标志来创建输出流对象,然后在写入时将其设置为ios::app。以下是一个示例代码:

#include <iostream>
#include <fstream>
using namespace std;
 
int main() {
    ofstream out(""d:\\example.txt", ios::app);
	time_t now = time(nullptr);
	char timestr[30];
	strftime(timestr, sizeof(timestr), "%y-%m-%d %h:%m:%s", localtime(&now));
	out << timestr << endl;
    out << "hello, world!" << endl;
    out << "this is an example." << endl;
    out.close();
    return 0;
}

在这个例子中,我们创建了一个名为“example.txt”的输出流对象,并将其设置为ios::app。然后,我们写入了两行文本,并在文件末尾添加了它们。最后,我们关闭了输出流对象。

若想在文件开头追加内容,可以使用ios::ate标志来创建输出流对象。这将导致输出流对象自动跳过文件开头的内容,并将下一个写入操作添加到文件末尾。以下是一个示例代码:

#include <iostream>
#include <fstream>
using namespace std;
 
int main() {
    ofstream out(""d:\\example.txt", ios::ate | ios::out);
	time_t now = time(nullptr);
	char timestr[30];
	strftime(timestr, sizeof(timestr), "%y-%m-%d %h:%m:%s", localtime(&now));
	out << timestr << endl;
    out << "this is an example." << endl;
    out << "hello, world!" << endl;
    out.close();
    return 0;
}

在这个例子中,我们创建了一个名为“example.txt”的输出流对象,并将其设置为ios::ate | ios::out。然后,我们写入了两行文本,并在文件末尾添加了它们。最后,我们关闭了输出流对象。

以上就是c#读取与写入txt文件内容的实现方法的详细内容,更多关于c#读取与写入txt内容的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com