您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在C#中,可以使用System.IO
命名空间中的类来实现文件的读写操作。以下是一些基本的文件读写操作的示例:
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
string content = "Hello, World!";
// 使用File.WriteAllText方法写入整个字符串到文件
File.WriteAllText(path, content);
// 或者使用StreamWriter来写入文本
using (StreamWriter writer = new StreamWriter(path))
{
writer.WriteLine(content);
}
}
}
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
// 使用File.ReadAllText方法读取整个文件内容到字符串
string content = File.ReadAllText(path);
Console.WriteLine(content);
// 或者使用StreamReader来逐行读取文件
using (StreamReader reader = new StreamReader(path))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
string additionalContent = "\nThis is additional content.";
// 使用File.AppendAllText方法追加文本到文件末尾
File.AppendAllText(path, additionalContent);
}
}
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
if (File.Exists(path))
{
Console.WriteLine("The file exists.");
}
else
{
Console.WriteLine("The file does not exist.");
}
}
}
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
if (File.Exists(path))
{
File.Delete(path);
Console.WriteLine("File deleted.");
}
else
{
Console.WriteLine("File does not exist.");
}
}
}
using System;
using System.IO;
class Program
{
static void Main()
{
string sourcePath = "source.txt";
string destinationPath = "destination.txt";
if (File.Exists(sourcePath))
{
File.Copy(sourcePath, destinationPath);
Console.WriteLine("File copied.");
}
else
{
Console.WriteLine("Source file does not exist.");
}
}
}
using System;
using System.IO;
class Program
{
static void Main()
{
string sourcePath = "source.txt";
string destinationPath = "destination.txt";
if (File.Exists(sourcePath))
{
File.Move(sourcePath, destinationPath);
Console.WriteLine("File moved or renamed.");
}
else
{
Console.WriteLine("Source file does not exist.");
}
}
}
在进行文件操作时,请确保处理可能出现的异常,例如IOException
、UnauthorizedAccessException
等。可以使用try-catch
块来捕获和处理这些异常。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。