C# tips and tricks 28 – FileInfo class | How to Create, Copy, Move, Rename and delete a file in C#

1
1



What is FileInfo?
FileInfo used for typical operations such as copying, moving, renaming, creating, opening, deleting and appending to files.

It uses StreamWriter class to write data and StreamReader class to read data to the file.

It is sealed class so we cannot be inherited.

FileInfo class Provides Methods and Properties.

FileInfo Parent class and namespace
FileInfo class is a System.IO namespace.

FileInfo’s Parent class is a FileSystemInfo.

FileInfo Properties
Attributes
CreationTime
CreationTime Utc
Directory
DirectoryName
Exists
Extension
FullName
IsReadOnly
LastAccessTime
LastAccessTimeUtc
LastWriteTime
LastWriteTimeUtc
Length
Name

FileInfo Methods
AppendText()
CopyTo()
Create()
CreateText()
Decrypt()
Delete()
Encrypt()
GetAccessControl()
GetLifetimeServices()
Replace()
InitializeLifetimeService()
MemberWiseClone()
MoveTo()
Open()
OpenRead()
OpenText()
OpenWrite()
Refresh()

Code for FileInfo class demo :

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FileInfoDemo
{
class Program
{
static void Main(string[] args)
{
//Create Method

FileInfo fi = new FileInfo(@”E:/file/MyTestFile.txt”);
FileStream fs = fi.Create();
Console.WriteLine(“File Has been Created”);

//CreateText Method

FileInfo fi = new FileInfo(@”E:/file/MyTestFile.txt”);
StreamWriter str = fi.CreateText();
str.WriteLine(“Ankpro”);
Console.WriteLine(“File has been Created with text”);
str.Close();

//Delete Method

FileInfo fi = new FileInfo(@”E:/file/MyTestFile.txt”);
fi.Delete();
Console.WriteLine(“File has been deleted”);

//copy method

string path = @”E:/file/MyTestFile.txt”;
string path2 = @”E:/copy/MyTestFile.txt”;
FileInfo f1 = new FileInfo(path);
FileInfo f2 = new FileInfo(path2);
f1.CopyTo(path2);
Console.WriteLine(“{0} was copied to {1}.” , path, path2);

// move method
string path = @”E:/file/Move.txt”;
string path2 = @”E:/copy/Move.txt”;
FileInfo f1 = new FileInfo(path);
FileInfo f2 = new FileInfo(path2);
f1.MoveTo(path2);
Console.WriteLine(“{0} was copied to {1}.”, path, path2);

//opentext method

FileInfo fi = new FileInfo(@”E:/file/MyTestFile.txt”);
StreamReader sr = fi.OpenText();
string s = “”;
while((s=sr.ReadLine())!=null)
{
Console.WriteLine(s);
}

FileInfo fi = new FileInfo(@”E:/file/MyTestFile.txt”);
Console.WriteLine(“File name is {0}”, fi.Name);
Console.WriteLine(“File Creation Time is {0}”, fi.CreationTime);
Console.WriteLine(“File LastAccess Time is {0}”, fi.LastAccessTime);
Console.WriteLine(“File Length is {0}”, fi.Length +”bytes”);

}
}
}

Nguồn:https://wijstaanvooronzegrondrechten.org/

Xem Thêm Bài Viết Khác:https://wijstaanvooronzegrondrechten.org/cong-nghe

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here