View Category
Read the contents of a file into a string
fantom
contents := File(`file.text`).readAllStr
csharp
string contents = System.IO.File.ReadAllText("filename.txt");
Process a file one line at a time
Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
1> First line of file
2> Second line of file
3> Third line of file
fantom
File(`input.text`).readAllLines.each |Str s, Int i| { echo("${i+1}> $s") }
csharp
int counter = 0;
// If the file is large, you would want to buffer this instead of reading everything at once
foreach (string line in System.IO.File.ReadAllLines("filename.txt"))
{
Console.WriteLine("{0}> {1}", ++counter, line);
}
// If the file is large, you would want to buffer this instead of reading everything at once
foreach (string line in System.IO.File.ReadAllLines("filename.txt"))
{
Console.WriteLine("{0}> {1}", ++counter, line);
}
Write a string to a file
fantom
File(`out.txt`).out.writeChars("some text").flush
csharp
System.IO.File.WriteAllText("filename.txt", "Some text to write to the file");
Append to a file
fantom
File(`out.txt`).out(true).writeChars("some text").flush
csharp
System.IO.File.AppendAllText("filename.txt", "Some text to append to the file");
Process each file in a directory
fantom
File(`./`).list.each { process(it) }
csharp
foreach (string filename in System.IO.Directory.GetFiles(directory)) ProcessFile(filename);
Process each file in a directory recursively
fantom
File(`./`).walk { process(it) }
