Techumber
Home Blog Work

BASIC FILE OPERATIONS CREATE,WRITE,READ,APPEND AND DELETE IN C#.NET

Published on October 12, 2012

In one of my previous article. I have written how to do basic file opertions in php. In this post i am going to explain how to do similar file operations in C# .NET. You can use it in your ASP.NET applications also. BASIC FILE OPERATIONS CREATE,WRITE,READ,APPEND AND DELETE IN C#.NET Create File

using System;
using System.IO;
namespace TU.FileOpDemo
{
class FileOp
{
static void Main(string[] args)
{
FileStream fs = null;
if (!File.Exists("file.txt"))
{
fs = File.Create("file.txt");

}
}
}
}

Write To File

using System;
using System.IO;
namespace TU.FileOpDemo
{
class FileOp
{
static void Main(string[] args)
{
if(File.Exists("file.txt"))
{
Console.WriteLine("Please enter new text:");
string newtext = Console.ReadLine();
File.WriteAllText("test.txt", newtext);
}
}
}
}

Read File

using System;
using System.IO;
namespace TU.FileOpDemo
{
class FileOp
{
static void Main(string[] args)
{
if(File.Exists("file.txt"))
{
string text = File.ReadAllText("file.txt");
Console.WriteLine("Reading file.....");
Console.WriteLine(text);
}
}
}
}

Append to File

using System;
using System.IO;
namespace TU.FileOpDemo
{
class FileOp
{
static void Main(string[] args)
{
if(File.Exists("file.txt"))
{
Console.WriteLine("Please enter new text:");
string newtext = Console.ReadLine();
File.AppendAllText("file.txt", newtext + Environment.NewLine);

}
}
}
}

Delete File

using System;
using System.IO;
namespace TU.FileOpDemo
{
class FileOp
{
static void Main(string[] args)
{
if(File.Exists("file.txt"))
{
File.Delete("file.txt");
}
}
}
}