溫馨提示×

c# fileinfo怎樣處理文件操作

c#
小樊
114
2024-11-21 01:55:06
欄目: 編程語言

在C#中,可以使用System.IO命名空間中的FileInfo類來處理文件操作。以下是一些常見的文件操作示例:

  1. 創建一個新的文件:
using System.IO;

string filePath = @"C:\example\newfile.txt";
File.Create(filePath);
  1. 讀取文件內容:
using System.IO;

string filePath = @"C:\example\file.txt";
string content = File.ReadAllText(filePath);
Console.WriteLine(content);
  1. 寫入文件內容:
using System.IO;

string filePath = @"C:\example\file.txt";
string content = "Hello, World!";
File.WriteAllText(filePath, content);
  1. 追加內容到文件:
using System.IO;

string filePath = @"C:\example\file.txt";
string content = "\nThis is a new line.";
File.AppendAllText(filePath, content);
  1. 刪除文件:
using System.IO;

string filePath = @"C:\example\file.txt";
File.Delete(filePath);
  1. 檢查文件是否存在:
using System.IO;

string filePath = @"C:\example\file.txt";
bool exists = File.Exists(filePath);
Console.WriteLine(exists);
  1. 獲取文件屬性(例如,文件大小、創建時間等):
using System.IO;

string filePath = @"C:\example\file.txt";
FileInfo fileInfo = new FileInfo(filePath);
long size = fileInfo.Length;
DateTime createdTime = fileInfo.CreationTime;
Console.WriteLine($"Size: {size} bytes, Created: {createdTime}");

這些示例展示了如何使用FileInfo類執行基本的文件操作。在實際項目中,你可能需要根據需求對這些操作進行調整,例如使用異常處理來確保程序的健壯性。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女