C Sharp File

From Leo's Notes
Last edited on 5 April 2015, at 23:01.

Here are some common file operations you can do in C#.

System.IO.File[edit | edit source]

Exists()[edit | edit source]

Checks whether a file exists.

if (File.Exists(@"C:\test.txt")) 

System.IO.Path[edit | edit source]

DirectorySeparatorChar[edit | edit source]

Returns the directory separator character depending on the platform.

Windows: \
Unix: /

GetFullPath()[edit | edit source]

Converts a relative path to a full path.

Path.GetFileNameWithoutExtension(@"test.txt")
-> returns "C:\test.txt", depending on your current working directory

GetDirectoryName()[edit | edit source]

Returns the directory path to the given file.

Path.GetDirectoryName(@"C:\dir\test\test.txt")
-> returns "C:\dir\test"

GetFileNameWithoutExtension()[edit | edit source]

Returns only the file name without extension

Path.GetFileNameWithoutExtension(@"C:\test.txt")
-> returns "test"

GetExtension()[edit | edit source]

Returns the '.ext' file extension.

Path.GetExtension(@"C:\test.txt")
-> returns ".txt"