In C# File Class and FileInfo Class, both have the same functionality but in FileInfo we have more control over the file. It Comes under the System.IO;
Namespace.
Stream writer comes under System.IO
, it provides a number of methods some of them you can find below
Let's See Some Examples.
string fileInfo = @"C:\Users\PC\Desktop\Example.txt";
using (StreamWriter streamWriter = new StreamWriter(fileInfo))
{
streamWriter.Write("this is new line");
}
string fileInfo = @"C:\Users\PC\Desktop\Example.txt";
FileStream fileStream = new FileStream(fileInfo, FileMode.CreateNew);
using (StreamWriter streamWriter = new StreamWriter(fileStream))
{
streamWriter.Write("this is another line");
}
Stream reader also comes under System.IO
, it provides a number of methods some of them you can find below
FileInfo fileInfo = new FileInfo(@"C:\Users\PC\Desktop\Example.txt");
using (StreamReader streamReader = fileInfo.OpenText())
{
var gettext = "";
while((gettext = streamReader.ReadLine()) != null)
{
Console.WriteLine(gettext);
}
}
Remove All the previous Text
Use the FileInfo
class for common operations such as copying, moving, renaming, creating, opening, deleting, and adding files.
If you perform multiple operations on the same file, it may be more efficient to use the FileInfo instance methods instead of the corresponding static methods in the file class, because a security check is not always required. Many FileInfo methods return different types of I / O when you create or open files. See specific FileInfo members such as Open, OpenRead, OpenText, CreateText
, or Create
for more information.
The FileInfo
class provides the following properties that you can use to obtain information about a file. See the property pages for an example of how to use each property.
Method | Usage |
---|---|
AppendText |
Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo. |
CopyTo |
Copies an existing file to a new file, disallowing the overwriting of an existing file. |
Create |
Creates a file. |
CreateText |
Creates a StreamWriter that writes a new text file. |
Delete |
Permanently deletes a file. |
Encrypt |
Encrypts a file so that only the account used to encrypt the file can decrypt it. |
Equals |
Determines whether the specified object is equal to the current object. |
MoveTo |
Moves a specified file to a new location, providing the option to specify a new file name. |
Open |
Opens a file in the specified mode. |
OpenRead |
Creates a read-only FileStream. |
OpenText |
Creates a StreamReader with UTF8 encoding that reads from an existing text file. |
OpenWrite |
Creates a write-only FileStream. |
Refresh |
Refreshes the state of the object. |
Replace |
Replaces the contents of a specified file with the file described by the current FileInfo object, deleting the original file, and creating a backup of the replaced file. |
ToString |
Returns the path as a string. Use the Name property for the full path. |