top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Describe C# FileInfo

0 votes
290 views

You have learned how to perform different tasks on physical files using static File class in the previous section. Here, we will use FileInfo class to perform read/write operation on physical files.

The FileInfo class provides the same functionality as the static File class but you have more control on read/write operations on files by writing code manually for reading or writing bytes from a file.

Important properties and methods of FileInfo:

Property Usage
Directory Gets an instance of the parent directory.
DirectoryName Gets a string representing the directory's full path.
Exists Gets a value indicating whether a file exists.
Extension Gets the string representing the extension part of the file.
FullName Gets the full path of the directory or file.
IsReadOnly Gets or sets a value that determines if the current file is read only.
LastAccessTime Gets or sets the time the current file or directory was last accessed
LastWriteTime Gets or sets the time when the current file or directory was last written to
Length Gets the size, in bytes, of the current file.
Name Gets the name of the file.
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.
Decrypt Decrypts a file that was encrypted by the current account using the Encrypt method.
Delete Deletes the specified file.
Encrypt Encrypts a file so that only the account used to encrypt the file can decrypt it.
GetAccessControl Gets a FileSecurity object that encapsulates the access control list (ACL) entries for a specified file.
MoveTo Moves a specified file to a new location, providing the option to specify a new file name.
Open Opens a in the specified FileMode.
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.
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 a path as string.

The following example shows how to read bytes from a file manually and then convert them to a string using UTF8 encoding:

//Create object of FileInfo for specified path            
FileInfo fi = new FileInfo(@"D:\DummyFile.txt");

//Open file for Read\Write
FileStream fs = fi.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); 

//create byte array of same size as FileStream length
byte[] fileBytes = new byte[fs.Length];

//define counter to check how much butes to read. Decrease the counter as you read each byte
int numBytesToRead = (int)fileBytes.Length;

//Counter to indicate number of bytes already read
int numBytesRead = 0;

//iterate till all the bytes read from FileStream
while (numBytesToRead > 0)
{
    int n = fs.Read(fileBytes, numBytesRead, numBytesToRead);
    if (n == 0)
        break;

    numBytesRead += n;
    numBytesToRead -= n;
}

//Once you read all the bytes from FileStream, you can convert it into string using UTF8 encoding
string filestring = Encoding.UTF8.GetString(fileBytes);

 

As you have seen in the above code, you have to write lot of code for reading/writing a string from a FileSream. The same read/write operation can be done easily using StreamReader and StreamWriter.

The following example shows how StreamReader makes it easy to read strings from a file:

//Create object of FileInfo for specified path            
FileInfo fi = new FileInfo(@"D:\DummyFile.txt");
        
//Open file for Read\Write
FileStream fs = fi.Open(FileMode.OpenOrCreate, FileAccess.Read , FileShare.Read); 

//Create object of StreamReader by passing FileStream object on which it needs to operates on
StreamReader sr = new StreamReader(fs);

//Use ReadToEnd method to read all the content from file
string fileContent = sr.ReadToEnd();

//Close StreamReader object after operation
sr.Close();
fs.Close();

Notice that fi.Open() has three parameters: The first parameter is FileMode for creating and opening a file if it does not exist; the second parameter, FileAccess, is to indicate a Read operation; and the third parameter is to share the file for reading with other users while the file is open.

The following example shows how StreamWriter makes it easy to write strings to a File:

Example: Write texts to file using StreamWriter

//Create object of FileInfo for specified path            
FileInfo fi = new FileInfo(@"D:\DummyFile.txt");
        
//Open file for Read\Write
FileStream fs = fi.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read ); 

//Create StreamWriter object to write string to FileSream
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("Another line from streamwriter");
sw.Close();

Read and Write operations are not possible on the same FileStream object simultaneously. If you are already reading from a file, create a separate FileStream object to write to the same file, as shown below:

//Create FileInfo object for DummyFile.txt
FileInfo fi = new FileInfo(@"D:\DummyFile.txt");

//open DummyFile.txt for read operation
FileStream fsToRead = fi.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite , FileShare.ReadWrite); 

//open DummyFile.txt for write operation
FileStream fsToWrite = fi.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); 
          
//get the StreamReader

StreamReader sr = new StreamReader(fsToRead);
//read all texts using StreamReader object
string fileContent = sr.ReadToEnd();
sr.Close();

//get the StreamWriter
StreamWriter sw = new StreamWriter(fsToWrite);
//write some text using StreamWriter
sw.WriteLine("Another line from streamwriter");
sw.Close();

//close all Stream objects
fsToRead.Close();
fsToWrite.Close();

Thus you can use FileInfo, StreamReader and StreamWriter class to read/write contents from physical file.

Points to Remember :

  1. Use FileInfo class to perform operations on physical files manually.
  2. Use StreamReader & StreamWriter class with FileInfo for reading or writing string from physical file.
posted Jan 25, 2017 by Shivaranjini

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

This tutorial demonstrates versioning in C# through the use of the override and new keywords. Versioning maintains compatibility between base and derived classes as they evolve.The C# language is designed such that versioning between base and derived classes in different libraries can evolve and maintain backwards compatibility. This means, for example, that the introduction of a new member in a base class with the same name as a member in a derived class is not an error. It also means that a class must explicitly state whether a method is intended to override an inherited method, or whether a method is a new method that simply hides a similarly named inherited method.

In C#, methods are by default, not virtual. To make a method virtual, the virtual modifier has to be used in the method declaration of the base class. The derived class can then override the base virtual method by using the override keyword or hide the virtual method in the base class by using thenew keyword. If neither the override keyword nor the new keyword is specified, the compiler will issue a warning and the method in the derived class will hide the method in the base class. The following example shows these concepts in action.

Example

// versioning.cs
// CS0114 expected
public class MyBase 
{
   public virtual string Meth1() 
   {
      return "MyBase-Meth1";
   }
   public virtual string Meth2() 
   {
      return "MyBase-Meth2";
   }
   public virtual string Meth3() 
   {
      return "MyBase-Meth3";
   }
}

class MyDerived : MyBase 
{
   // Overrides the virtual method Meth1 using the override keyword:
   public override string Meth1() 
   {
      return "MyDerived-Meth1";
   }
   // Explicitly hide the virtual method Meth2 using the new
   // keyword:
   public new string Meth2() 
   {
      return "MyDerived-Meth2";
   }
   // Because no keyword is specified in the following declaration
   // a warning will be issued to alert the programmer that 
   // the method hides the inherited member MyBase.Meth3():
   public string Meth3() 
   {
      return "MyDerived-Meth3";
   }

   public static void Main() 
   {
      MyDerived mD = new MyDerived();
      MyBase mB = (MyBase) mD;

      System.Console.WriteLine(mB.Meth1());
      System.Console.WriteLine(mB.Meth2());
      System.Console.WriteLine(mB.Meth3());
   }
}

Output

MyDerived-Meth1
MyBase-Meth2
MyBase-Meth3

Code Discussion

Hiding a base class member from a derived class isn't an error in C#. This feature enables you to make changes in the base class without breaking other libraries that inherit this base class. For example, at some point you could have the following classes:

class Base {}
class Derived: Base
{
   public void F() {}
}

At some later point, the base class could evolve to add a void method F() as follows:

class Base 
{
   public void F() {}
}
class Derived: Base
{
   public void F() {}
}

Thus, in C#, both the base and derived classes can evolve freely and maintain binary compatibility.

 

READ MORE

An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable. For example, assume that you have to define a variable whose value will represent a day of the week. There are only seven meaningful values which that variable will ever store. To define those values, you can use an enumeration type, which is declared by using the enum keyword.

C#

enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
enum Months : byte { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }; 

By default the underlying type of each element in the enum is int. You can specify another integral numeric type by using a colon, as shown in the previous example. For a full list of possible types

 

You can verify the underlying numeric values by casting to the underlying type, as the following example shows.

C#

Days today = Days.Monday;
int dayNumber =(int)today;
Console.WriteLine("{0} is day number #{1}.", today, dayNumber);

Months thisMonth = Months.Dec;
byte monthNumber = (byte)thisMonth;
Console.WriteLine("{0} is month number #{1}.", thisMonth, monthNumber);

// Output:
// Monday is day number #1.
// Dec is month number #11.

The following are advantages of using an enum instead of a numeric type:

  • You clearly specify for client code which values are valid for the variable.

  • In Visual Studio, IntelliSense lists the defined values.

When you do not specify values for the elements in the enumerator list, the values are automatically incremented by 1. In the previous example,Days.Sunday has a value of 0, Days.Monday has a value of 1, and so on. When you create a new Days object, it will have a default value of Days.Sunday (0) if you do not explicitly assign it a value. When you create an enum, select the most logical default value and give it a value of zero. That will cause all enums to have that default value if they are not explicitly assigned a value when they are created.

If the variable meetingDay is of type Days, then (without an explicit cast) you can only assign it one of the values defined by Days. And if the meeting day changes, you can assign a new value from Days to meetingDay:

C#

Days meetingDay = Days.Monday;
//...
meetingDay = Days.Friday;
 

It is possible to assign any arbitrary integer value to meetingDay. For example, this line of code does not produce an error: meetingDay = (Days) 42. However, you should not do this because the implicit expectation is that an enum variable will only hold one of the values defined by the enum. To assign an arbitrary value to a variable of an enumeration type is to introduce a high risk for errors.

You can assign any values to the elements in the enumerator list of an enumeration type, and you can also use computed values:

C#

enum MachineState
{
    PowerOff = 0,
    Running = 5,
    Sleeping = 10,
    Hibernating = Sleeping + 5
}

Enumeration Types as Bit Flags

You can use an enumeration type to define bit flags, which enables an instance of the enumeration type to store any combination of the values that are defined in the enumerator list. (Of course, some combinations may not be meaningful or allowed in your program code.)

You create a bit flags enum by applying the System.FlagsAttribute attribute and defining the values appropriately so that ANDORNOT and XORbitwise operations can be performed on them. In a bit flags enum, include a named constant with a value of zero that means "no flags are set." Do not give a flag a value of zero if it does not mean "no flags are set".

In the following example, another version of the Days enum, which is named Days2, is defined. Days2 has the Flags attribute and each value is assigned the next greater power of 2. This enables you to create a Days2 variable whose value is Days2.Tuesday and Days2.Thursday.

C#

[Flags]
enum Days2
{
    None = 0x0,
    Sunday = 0x1,
    Monday = 0x2,
    Tuesday = 0x4,
    Wednesday = 0x8,
    Thursday = 0x10,
    Friday = 0x20,
    Saturday = 0x40
}
class MyClass
{
    Days2 meetingDays = Days2.Tuesday | Days2.Thursday;
}

To set a flag on an enum, use the bitwise OR operator as shown in the following example:

// Initialize with two flags using bitwise OR.
meetingDays = Days2.Tuesday | Days2.Thursday;

// Set an additional flag using bitwise OR.
meetingDays = meetingDays | Days2.Friday;

Console.WriteLine("Meeting days are {0}", meetingDays);
// Output: Meeting days are Tuesday, Thursday, Friday

// Remove a flag using bitwise XOR.
meetingDays = meetingDays ^ Days2.Tuesday;
Console.WriteLine("Meeting days are {0}", meetingDays);
// Output: Meeting days are Thursday, Friday

To determine whether a specific flag is set, use a bitwise AND operation, as shown in the following example:

// Test value of flags using bitwise AND.
bool test = (meetingDays & Days2.Thursday) == Days2.Thursday;
Console.WriteLine("Thursday {0} a meeting day.", test == true ? "is" : "is not");
// Output: Thursday is a meeting day.

Using the System.Enum Methods to Discover and Manipulate Enum Values

All enums are instances of the System.Enum type. You cannot derive new classes from System.Enum, but you can use its methods to discover information about and manipulate values in an enum instance.

string s = Enum.GetName(typeof(Days), 4);
Console.WriteLine(s);

Console.WriteLine("The values of the Days Enum are:");
foreach (int i in Enum.GetValues(typeof(Days)))
    Console.WriteLine(i);

Console.WriteLine("The names of the Days Enum are:");
foreach (string str in Enum.GetNames(typeof(Days)))
    Console.WriteLine(str);
READ MORE


Here I will explain what is delegates in c#.net with example. Basically delegates in c# are type safe objects which are used to hold reference of one or more methods in c#.net. Delegates concept will match with pointer concept of c language.

Whenever we want to create delegate methods we need to declare with delegate keyword and delegate methods signature should match exactly with the methods which we are going to hold like same return types and same parameters otherwise delegate functionality won’t work if signature not match with methods.

 

Syntax of Delegate & Methods Declaration

public delegate int Delegatmethod(int a,int b);

public class Sampleclass

{

public int Add(int x, int y)

{

return x + y;

}

public int Sub(int x, int y)

{

return x + y;

}

}

 

If you observe above code I declared Delegatmethod method with two parameters which matching with methods declared in Sampleclass class.

 

Complete Example

public delegate int DelegatSample(int a,int b);

public class Sampleclass

{

public int Add(int x, int y)

{

return x + y;

}

public int Sub(int x, int y)

{

return x - y;

}

}

class Program

{

static void Main(string[] args)

{

Sampleclass sc=new Sampleclass();

 

DelegatSample delgate1 = sc.Add;

int i = delgate1(10, 20);

Console.WriteLine(i);

DelegatSample delgate2 = sc.Sub;

int j = delgate2(20, 10);

Console.WriteLine(j);

}

}

Output

Add Result : 30

Sub Result : 10

 

What is the use of Delegates?

 

Suppose if you have multiple methods with same signature (return type & number of parameters) and want to call all the methods with single object then we can go for delegates.

 

Delegates are two types

 

      -   Single Cast Delegates

      -  Multi Cast Delegates

 

Single Cast Delegates

 

Single cast delegate means which hold address of single method like as explained in above example.

 

Multicast Delegates

 

Multi cast delegate is used to hold address of multiple methods in single delegate. To hold multiple addresses with delegate we will use overloaded += operator and if you want remove addresses from delegate we need to use overloaded operator -=

 

Syntax of Multicast Delegate & Method Declaration

public delegate void MultiDelegate(int a,int b);

public class Sampleclass

{

public static void Add(int x, int y)

{

Console.WriteLine("Addition Value: "+(x + y));

}

public static void Sub(int x, int y)

{

Console.WriteLine("Subtraction Value: " + (x - y));

}

public static void Mul(int x, int y)

{

Console.WriteLine("Multiply Value: " + (x * y));

}

}


if you observe above code I declared MultiDelegate method with void return type.

Complete Example

 

 

public delegate void MultiDelegate(int a,int b);

public class Sampleclass

{

public static void Add(int x, int y)

{

Console.WriteLine("Addition Value: "+(x + y));

}

public static void Sub(int x, int y)

{

Console.WriteLine("Subtraction Value: " + (x - y));

}

public static void Mul(int x, int y)

{

Console.WriteLine("Multiply Value: " + (x * y));

}

}

class Program

{

static void Main(string[] args)

{

Sampleclass sc=new Sampleclass();

MultiDelegate del = Sampleclass.Add;

del += Sampleclass.Sub;

del += Sampleclass.Mul;

del(10, 5);

Console.ReadLine();

}

}

 

Output: Whenever we run above code we will get output like as shown below

Addition Value:15

Subtraction Value: 5

Multiply Value:50

READ MORE
...