Programming Fundamentals/Files/C Sharp
Appearance
files.cs
[edit | edit source]// This program creates a file, adds data to the file, displays the file,
// appends more data to the file, displays the file, and then deletes the file.
// It will not run if the file already exists.
//
// References:
// https://www.mathsisfun.com/temperature-conversion.html
// https://en.wikibooks.org/wiki/C_Sharp_Programming
using System;
public class Files
{
public static void Main(String[] args)
{
string FILENAME = "~file.txt";
if(System.IO.File.Exists(FILENAME))
{
System.Console.WriteLine("File already exists.\n");
}
else
{
CreateFile(FILENAME);
ReadFile(FILENAME);
AppendFile(FILENAME);
ReadFile(FILENAME);
DeleteFile(FILENAME);
}
}
private static void CreateFile(string filename)
{
System.IO.StreamWriter file;
float c;
float f;
file = System.IO.File.CreateText(filename);
file.WriteLine("C\tF");
for(c = 0; c <= 50; c++)
{
f = c * 9 / 5 + 32;
file.WriteLine(c + "\t" + f);
}
file.Close();
}
private static void ReadFile(string filename)
{
System.IO.StreamReader file;
string line;
file = System.IO.File.OpenText(filename);
while (true)
{
line = file.ReadLine();
if (line == null)
{
break;
}
Console.WriteLine(line);
}
file.Close();
Console.WriteLine("");
}
private static void AppendFile(string filename)
{
System.IO.StreamWriter file;
float c;
float f;
file = System.IO.File.AppendText(filename);
for(c = 51; c <= 100; c++)
{
f = c * 9 / 5 + 32;
file.WriteLine(c + "\t" + f);
}
file.Close();
}
private static void DeleteFile(string filename)
{
System.IO.File.Delete(filename);
}
}
Try It
[edit | edit source]Copy and paste the code above into one of the following free online development environments or use your own C Sharp compiler / interpreter / IDE.