Parameter Details
path The locationof thefile.
append Ifthefileexist,truewilladddatatotheendofthefile(append),falsewilloverwritethefile. text Text to be written or stored.
contents A collection of strings to be written.
source The location of the file you want to use.
dest The location you want a file to go to.
Managesfiles.
Section97.1:ReadingfromafileusingtheSystem.IO.Fileclass
YoucanusetheSystem.IO.File.ReadAllTextfunctiontoreadtheentirecontentsofafileintoastring.
stringtext=System.IO.File.ReadAllText(@”C:\MyFolder\MyTextFile.txt”);
YoucanalsoreadafileasanarrayoflinesusingtheSystem.IO.File.ReadAllLinesfunction:
string[]lines=System.IO.File.ReadAllLines(@”C:\MyFolder\MyTextFile.txt”);
Section97.2:Lazilyreadingafileline-by-lineviaan IEnumerable
When working with large files, you can use the System.IO.File.ReadLinesmethod to read all lines from a file into anIEnumerable<string>.ThisissimilartoSystem.IO.File.ReadAllLines,exceptthatitdoesn’tloadthewholefile intomemoryatonce,makingitmoreefficientwhenworkingwithlargefiles.
IEnumerable<string>AllLines=File.ReadLines(“file_name.txt”,Encoding.Default);
ThesecondparameterofFile.ReadLinesisoptional.Youmayuseitwhenitisrequiredtospecifyencoding.
ItisimportanttonotethatcallingToArray,ToListoranothersimilarfunctionwillforceallofthelinestobeloaded atonce,meaningthatthebenefitofusingReadLinesisnullified.ItisbesttoenumerateovertheIEnumerableusing a foreachloop or LINQ if using this method.
Section 97.3: Asyncwrite textto afile usingStreamWriter
//filenameisastringwiththefullpath
//trueistoappend
using(System.IO.StreamWriterfile=newSystem.IO.StreamWriter(filename,true))
{
//Canwriteeitherastringorchararray
awaitfile.WriteAsync(text);
}
Filestaticclass
Filestaticclasscanbeeasilyusedforthispurpose.
File.Copy(@”sourcePath\abc.txt”,@”destinationPath\abc.txt”); File.Copy(@”sourcePath\abc.txt”,@”destinationPath\xyz.txt”);
Remark:Bythismethod,fileiscopied,meaningthatitwillbereadfromthesourceandthenwrittentothe destinationpath.Thisisaresourceconsumingprocess,itwouldtakerelativetimetothefilesize,andcancause your program to freeze if you don’t utilize threads.
Section97.5:Writinglinestoafileusingthe System.IO.StreamWriterclass
TheSystem.IO.StreamWriterclass:
ImplementsaTextWriterforwritingcharacterstoastreaminaparticularencoding.
UsingtheWriteLinemethod,youcanwritecontentline-by-linetoafile.
Notice the use of the usingkeyword which makes sure the StreamWriter object is disposed as soon as it goes out of scope and thus the file is closed.
string[]lines={“Myfirststring”,”Mysecondstring”,”andevenathirdstring”};
using(System.IO.StreamWritersw=newSystem.IO.StreamWriter(@”C:\MyFolder\OutputText.txt”))
{
foreach(stringlineinlines)
{
sw.WriteLine(line);
}
}
Note that the StreamWriter can receive a second boolparameter in it’s constructor, allowing to Appendto a file instead of overwriting the file:
boolappendExistingFile=true;
using(System.IO.StreamWritersw=newSystem.IO.StreamWriter(@”C:\MyFolder\OutputText.txt”, appendExistingFile))
{
sw.WriteLine(“Thislinewillbeappendedtotheexistingfile”);
}
Section97.6:WritingtoafileusingtheSystem.IO.Fileclass
YoucanusetheSystem.IO.File.WriteAllTextfunctiontowriteastringtoafile.
stringtext=”Stringthatwillbestoredinthefile”;
System.IO.File.WriteAllText(@”C:\MyFolder\OutputFile.txt”,text);
You can also use the System.IO.File.WriteAllLinesfunction which receives an IEnumerable<String>as the second parameter(asopposedtoasinglestringinthepreviousexample).Thisletsyouwritecontentfromanarrayoflines.
string[]lines={“Myfirststring”,”Mysecondstring”,”andevenathirdstring”}; System.IO.File.WriteAllLines(@”C:\MyFolder\OutputFile.txt”,lines);
Filestaticclass
ByusingCreatemethodoftheFilestaticclasswecancreatefiles.Methodcreatesthefileatthegivenpath,atthe sametimeitopensthefileandgivesustheFileStreamofthefile.Makesureyouclosethefileafteryouaredone with it.
ex1:
varfileStream1=File.Create(“samplePath”);
///youcanwritetothefileStream1
fileStream1.Close();
ex2:
using(varfileStream1=File.Create(“samplePath”))
{
///youcanwritetothefileStream1
}
ex3:
File.Create(“samplePath”).Close();
FileStreamclass
Therearemanyoverloadsofthisclassesconstructorwhichisactuallywelldocumentedhere.Belowexampleisfor the one that covers most used functionalities of this class.
varfileStream2=newFileStream(“samplePath”,FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None);
You can check the enums for FileMode, FileAccess, and FileSharefrom those links. What they basically means are asfollows:
FileMode:Answers”Shouldfilebecreated?opened?createifnotexistthenopen?”kindaquestions.
FileAccess:Answers”ShouldIbeabletoreadthefile,writetothefileorboth?”kindaquestions.
FileShare:Answers”Shouldotherusersbeabletoread,writeetc.tothefilewhileIamusingitsimultaneously?” kinda questions.
Filestaticclass
Filestaticclasscaneasilybeusedforthispurpose.
File.Move(@”sourcePath\abc.txt”,@”destinationPath\xyz.txt”);
Remark1: Onlychangestheindexofthefile(ifthefileismovedinthesamevolume).Thisoperationdoesnottake relative time to the file size.
Remark2:Cannotoverrideanexistingfileondestinationpath.
stringpath=@”c:\path\to\file.txt”;
File.Delete(path);
While Deletedoes not throw exception if file doesn’t exist, it will throw exception e.g. if specified path is invalid or caller does not have the required permissions. You should always wrap calls to Deleteinside try-catch block and handle all expected exceptions. In case of possible race conditions, wrap logic inside lock statement.
Section97.10:FilesandDirectories
GetallfilesinDirectory
varFileSearchRes=Directory.GetFiles(@Path,”*.*”,SearchOption.AllDirectories);
ReturnsanarrayofFileInfo,representingallthefilesinthespecifieddirectory.
GetFileswithspecificextension
varFileSearchRes=Directory.GetFiles(@Path,”*.pdf”,SearchOption.AllDirectories);
ReturnsanarrayofFileInfo,representingallthefilesinthespecifieddirectorywiththespecifiedextension.
About us and this blog
We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.
Request a free quote
We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.
Subscribe to our newsletter!
More from our blog
See all postsRecent Posts
- Chapter110:Timers 10/05/2024
- Chapter109:Stream 09/05/2024
- Chapter108:CheckedandUnchecked 08/05/2024