Skip to content
guryanovev edited this page Dec 8, 2015 · 2 revisions

IFile is a class representing single file. It contains properties and methods to perform typical files-related tasks.

IFile class members

AbsolutePath

Gets file "absolute" path. It is the path the file was originaly created with:

IFile solutionFile = "C:/Projects/MyProject.sln";

string path = solutionFile.AbsolutePath; // path is C:/Projects/MyProject.sln

...or the path derived from parent directory:

IDirectory src = "C:/Projects/MyProject"
IFile solutionFile = src/"MyProject.sln";

string path = solutionFile.AbsolutePath; // path is C:/Projects/MyProject/MyProject.sln

There is an implicit to string conversion operation that returns AbsolutePath so the call to this property could be omited:

IFile solutionFile = "C:/Projects/MyProject.sln";

// implicit conversion
string path = solutionFile; // path is C:/Projects/MyProject.sln
Exists

Gets the flag indicating whether the file exists.

IFile solutionFile = "C:/Projects/MyProject.sln";

bool solutionFileExists = solutionFile.Exists;
Name

Gets file name with extension without preceding path.

IFile solutionFile = "C:/Projects/MyProject.sln";

string fileName = solutionFile.Name; // MyProject.sln
NameWithoutExtension

Gets file name without extension.

IFile solutionFile = "C:/Projects/MyProject.sln";

string fileName = solutionFile.NameWithoutExtension; // MyProject
ReadStream

Gets file reading stream.

IFile dataFile = "C:/Projects/data.txt";

using(var reader = new StreamReader(dataFile.ReadStream))
{
    // reading data
}
WriteStream

Gets file writing stream.

IFile dataFile = "C:/Projects/data.txt";

using (var writer = new StreamWriter(dataFile.WriteStream))
{
    // writing data
}
Extension

Gets an object of type ExtensionInfo that encapsulates information about file extension.

Length

Gets size of the file in bytes.

Directory

Gets parent directory object (IDirectory) of the file.

EnsureExists()

Creates file (and it's parent directory) if it does not exist.

IFile dataFile = "C:/Projects/data.txt";

// creates C:/Projects (if it does not exist) 
// directory and empty data.txt file:
dataFile.EnsureExists(); 
Delete()

Deletes the file.

GetRelativePath(IDirectory directory)

Calclulates relative path from provided directory to current file.

IFile file = "C:/A/B/file.txt";
IDirectory dir = "C:/A/D";

string relativeFilePath = file.GetRelativePath(dir); // "../B/file.txt"