C# tips and tricks 28 - FileInfo class | How to Create, Copy, Move, Created time & delete a file

preview_player
Показать описание
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

FileStream fs = fi.Create();
Console.WriteLine("File Has been Created");

//CreateText Method

StreamWriter str = fi.CreateText();
str.WriteLine("Ankpro");
Console.WriteLine("File has been Created with text");
str.Close();

//Delete Method

fi.Delete();
Console.WriteLine("File has been deleted");

//copy method

FileInfo f1 = new FileInfo(path);
FileInfo f2 = new FileInfo(path2);
f1.CopyTo(path2);
Console.WriteLine("{0} was copied to {1}." , path, path2);

// move method
FileInfo f1 = new FileInfo(path);
FileInfo f2 = new FileInfo(path2);
f1.MoveTo(path2);
Console.WriteLine("{0} was copied to {1}.", path, path2);

//opentext method

StreamReader sr = fi.OpenText();
string s = "";
while((s=sr.ReadLine())!=null)
{
Console.WriteLine(s);
}


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");

}
}
}
Рекомендации по теме
Комментарии
Автор

What is the difference between filestream and fileinfo and streamwriter and text write and when to use all these classes

abdulkadir-jhyj
Автор

How to check if a file has password with dotnezip, Opening another Form to enter the password.

valleyview