Export (0) Print
Expand All

FileInfo Constructor

Initializes a new instance of the FileInfo class, which acts as a wrapper for a file path.

[Visual Basic]
Public Sub New( _
   ByVal fileName As String _
)
[C#]
public FileInfo(
   string fileName
);
[C++]
public: FileInfo(
   String* fileName
);
[JScript]
public function FileInfo(
   fileName : String
);

Parameters

fileName
The fully qualified name of the new file, or the relative file name.

Exceptions

Exception Type Condition
ArgumentNullException fileName is a null reference (Nothing in Visual Basic).
SecurityException The caller does not have the required permission.
ArgumentException The file name is empty, contains only white spaces, or contains invalid characters.
UnauthorizedAccessException Access to fileName is denied.
PathTooLongException The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
NotSupportedException fileName contains a colon (:) in the middle of the string.

Remarks

You can specify either the fully qualified or the relative file name, but the security check gets the fully qualified name.

For an example of using this method, see the Example section below. The following table lists examples of other typical or related I/O tasks.

To do this... See the example in this topic...
Create a text file. Writing Text to a File
Write to a text file. Writing Text to a File
Read from a text file. Reading Text from a File
Append text to a file. Opening and Appending to a Log File

File.AppendText

FileInfo.AppendText

Rename or move a file. File.Move

FileInfo.MoveTo

Delete a file. File.Delete

FileInfo.Delete

Copy a file. File.Copy

FileInfo.CopyTo

Get the size of a file. FileInfo.Length
Get the attributes of a file. File.GetAttributes
Set the attributes of a file. File.SetAttributes
Determine if a file exists. File.Exists
Read from a binary file. Reading and Writing to a Newly Created Data File
Write to a binary file. Reading and Writing to a Newly Created Data File
Retrieve a file extension. Path.GetExtension
Retrieve the fully qualified path of a file. Path.GetFullPath
Retrieve the file name and extension from a path. Path.GetFileName
Change the extension of a file. Path.ChangeExtension

Example

The following example uses this constructor to create two files, which are then written to, read from, copied, and deleted.

[Visual Basic] 
Imports System
Imports System.IO

Class Test

    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"
        Dim fi1 As FileInfo = New FileInfo(path)

        If fi1.Exists = False Then
            'Create a file to write to.
            Dim sw As StreamWriter = fi1.CreateText()
            sw.WriteLine("Hello")
            sw.WriteLine("And")
            sw.WriteLine("Welcome")
            sw.Flush()
            sw.Close()
        End If

        'Open the file to read from.
        Dim sr As StreamReader = fi1.OpenText()

        Do While sr.Peek() >= 0
            Console.WriteLine(sr.ReadLine())
        Loop

        Try
            Dim path2 As String = path + "temp"
            Dim fi2 As FileInfo = New FileInfo(path2)

            'Ensure that the target does not exist.
            fi2.Delete()

            'Copy the file.
            fi1.CopyTo(path2)
            Console.WriteLine("{0} was copied to {1}.", path, path2)

            'Delete the newly created file.
            fi2.Delete()
            Console.WriteLine("{0} was successfully deleted.", path2)

        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

[C#] 
using System;
using System.IO;

class Test 
{
    
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";
        FileInfo fi1 = new FileInfo(path);

        if (!fi1.Exists) 
        {
            //Create a file to write to.
            using (StreamWriter sw = fi1.CreateText()) 
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }    
        }

        //Open the file to read from.
        using (StreamReader sr = fi1.OpenText()) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                Console.WriteLine(s);
            }
        }

        try 
        {
            string path2 = path + "temp";
            FileInfo fi2 = new FileInfo(path2);

            //Ensure that the target does not exist.
            fi2.Delete();

            //Copy the file.
            fi1.CopyTo(path2);
            Console.WriteLine("{0} was copied to {1}.", path, path2);

            //Delete the newly created file.
            fi2.Delete();
            Console.WriteLine("{0} was successfully deleted.", path2);

        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}

[C++] 
#using <mscorlib.dll>

using namespace System;
using namespace System::IO;

int main() {
    String* path = S"c:\\temp\\MyTest.txt";
    FileInfo* fi1 = new FileInfo(path);

    if (!fi1->Exists) {
        //Create a file to write to.
        StreamWriter* sw = fi1->CreateText();
        try {
            sw->WriteLine(S"Hello");
            sw->WriteLine(S"And");
            sw->WriteLine(S"Welcome");
        } __finally {
            if (sw) __try_cast<IDisposable*>(sw)->Dispose();
        }
    }

    //Open the file to read from.
    StreamReader* sr = fi1->OpenText();
    try {
        String* s = S"";
        while (s = sr->ReadLine()) {
            Console::WriteLine(s);
        }
    } __finally {
        if (sr) __try_cast<IDisposable*>(sr)->Dispose();
    }

    try {
        String* path2 = String::Concat(path, S"temp");
        FileInfo* fi2 = new FileInfo(path2);

        //Ensure that the target does not exist.
        fi2->Delete();

        //Copy the file.
        fi1->CopyTo(path2);
        Console::WriteLine(S"{0} was copied to {1}.", path, path2);

        //Delete the newly created file.
        fi2->Delete();
        Console::WriteLine(S"{0} was successfully deleted.", path2);
    } catch (Exception* e) {
        Console::WriteLine(S"The process failed: {0}", e);
    }
}

The following example opens an existing file or creates a file, appends text to the file, and displays the results.

[Visual Basic] 
Imports System
Imports System.IO

Public Class FileInfoMainTest

    Public Shared Sub Main()
        ' Open an existing file, or create a new one.
        Dim fi As New FileInfo("temp.txt")
        ' Create a writer, ready to add entries to the file.
        Dim sw As StreamWriter = fi.AppendText()
        sw.WriteLine("This is a new entry to add to the file")
        sw.WriteLine("This is yet another line to add...")
        sw.Flush()
        sw.Close()
        Dim sr As New StreamReader(fi.OpenRead())
        ' Get the information out of the file and display it.
        While sr.Peek() <> -1
            Console.WriteLine(sr.ReadLine())
        End While
    End Sub 'Main
End Class 'FileInfoMainTest

[C#] 
using System;
using System.IO;

public class FileInfoMainTest 
{
    public static void Main() 
    {
        // Open an existing file, or create a new one.
        FileInfo fi = new FileInfo("temp.txt");
        // Create a writer, ready to add entries to the file.
        StreamWriter sw = fi.AppendText();
        sw.WriteLine("This is a new entry to add to the file");
        sw.WriteLine("This is yet another line to add...");
        sw.Flush();
        sw.Close();
        // Get the information out of the file and display it.
        StreamReader sr = new StreamReader( fi.OpenRead() );
        while (sr.Peek() != -1)
            Console.WriteLine( sr.ReadLine() );
    }
}

[C++] 
#using <mscorlib.dll>

using namespace System;
using namespace System::IO;

int main() {
    // Open an existing file, or create a new one.
    FileInfo* fi = new FileInfo(S"temp.txt");
    // Create a writer, ready to add entries to the file.
    StreamWriter* sw = fi->AppendText();
    sw->WriteLine(S"This is a new entry to add to the file");
    sw->WriteLine(S"This is yet another line to add...");
    sw->Flush();
    sw->Close();
    // Get the information out of the file and display it.
    StreamReader* sr = new StreamReader(fi->OpenRead());
    while (sr->Peek() != -1)
        Console::WriteLine(sr->ReadLine());
}

[JScript] 
import System;
import System.IO;

public class FileInfoMainTest {
    public static function Main() : void {

        // Open an existing file, or create a new one.
        var fi : FileInfo = new FileInfo("temp.txt");
        // Create a writer, ready to add entries to the file.
        var sw : StreamWriter = fi.AppendText();
        sw.WriteLine("This is a new entry to add to the file");
        sw.WriteLine("This is yet another line to add...");
        sw.Flush();
        sw.Close();
        // Get the information out of the file and display it.
        var sr : StreamReader = new StreamReader( fi.OpenRead() );
        while (sr.Peek() != -1)
            Console.WriteLine( sr.ReadLine() );
    }
}
FileInfoMainTest.Main();

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

.NET Framework Security: 

See Also

FileInfo Class | FileInfo Members | System.IO Namespace | Working with I/O | Reading Text from a File | Writing Text to a File

Show:
© 2014 Microsoft