Home

Files Operations

 

File Information

 

Introduction

In its high level of support for file processing, the .NET Framework provides a class named FileInfo. This class is equipped to handle all types of file-related operations including creating, copying, moving, renaming, or deleting a file. FileInfo is based on the FileSystemInfo class that provides information on characteristics of a file:

type FileInfo = 
    class 
        inherit FileSystemInfo 
    end

Initializing File Information

The FileInfo class is equipped with one constructor whose signature is:

new : 
        fileName:string -> FileInfo

This constructor takes as argument the name of a file or its complete path. If you provide only the name of the file, the compiler would consider the same directory of its project. Here is an example:

open System
open System.IO
open System.Windows.Forms

let exercise : Form = new Form()

let strFilename = "C:\\Resources\\Employees.spr"

let flePeople : FileInfo = new FileInfo(strFilename)

[<STAThread>]
[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

Alternatively, if you want, you can provide any valid directory you have access to. In this case, you should provide the complete path.

After creating a file, you can write one or more values to it. An example of a value is text. If you want to create a file that contains text, the FileInfo class provides a method named CreateText . Its signature is:

member CreateText : unit -> StreamWriter

This method returns a StreamWriter object. You can use this returned object to write text to the file.

Writing a Value to a File

To write normal text to a file, you can first call the FileInfo.CreateText() method. This method returns a StreamWriter object:

type StreamWriter =
    class
        inherit TextWriter
    end

The StreamWriter class is based on the TextWriter class:

type TextWriter =  
    class 
        inherit MarshalByRefObject 
        interface IDisposable 
    end

That class is equipped with the Write() and the WriteLine() methods used to write values to a file. The Write() method writes text on a line and keeps the caret on the same line. The WriteLine() method writes a line of text and moves the caret to the next line.

After writing to a file, you should close the StreamWriter object to free the resources it was using during its operation(s). Here is an example:

Writing a Value to a File

open System
open System.IO
open System.Drawing
open System.Windows.Forms

let allocate1 amount ratio1 ratio2 =
    let totalRatios = ratio1 + ratio2
    let eachPart = amount / totalRatios
    let part1 = eachPart * ratio1
    part1

let allocate2 amount ratio1 ratio2 =
    let totalRatios : float = ratio1 + ratio2
    let eachPart : float    = amount / totalRatios
    let part2 : float       = eachPart * ratio2
    part2

// Form: Ratio
let ratio : Form = new Form(ClientSize = new System.Drawing.Size(268, 178), Text = "Ratio")

// Label: Allocate
ratio.Controls.Add(new Label(AutoSize = true, Location = new Point(22, 19),
                                    Width = 60, Text = "Allocate:"))

// Text Box: Allocate
let txtAllocate : TextBox = new TextBox(Location = new Point(88, 16), Width = 79)
ratio.Controls.Add txtAllocate

// Label: In the ratio
ratio.Controls.Add(new Label(Width = 65, Text = "In the ratio:",
                             AutoSize = true, Location = new Point(22, 54)))

// Text Box: Part1
let txtPart1 : TextBox = new TextBox(Location = new Point(88, 51), Width = 31)
ratio.Controls.Add txtPart1

// Label: Colon
ratio.Controls.Add(new Label(Width = 10, Text = ":",
                             AutoSize = true, Location = new Point(123, 54)))

// Text Box: Part2
let txtPart2 : TextBox = new TextBox(Location = new Point(136, 51), Width = 31)
ratio.Controls.Add txtPart2

// Button: Allocate
let btnAllocate : Button = new Button(Location = new Point(173, 49), Text = "Allocate")

// Label: Line
ratio.Controls.Add(new Label(Size = new System.Drawing.Size(245, 1),
                             Location = new Point(12, 84), BackColor = Color.Black))

// Label: Part 1 Receives
ratio.Controls.Add(new Label(Location = new Point(22, 102),
                             AutoSize = true, Text = "Part 1 Receives:"))

// Text Box: Part 1 Value
let txtPart1Value : TextBox = new TextBox(Location = new Point(114, 99), Width = 53)
ratio.Controls.Add txtPart1Value

// Label: Part 2 Receives
ratio.Controls.Add(new Label(Width =  90, Text = "Part 2 Receives:",
                             AutoSize = true, Location = new Point(22, 138)))

let txtPart2Value : TextBox = new TextBox(Location = new Point(114, 135), Width = 53)
ratio.Controls.Add txtPart2Value

// Button: Close
let btnClose : Button = new Button(Location = new Point(173, 133), Text = "Close")

let btnAllocateClick e =
    let amount : float = float txtAllocate.Text
    let ratio1 : float = float txtPart1.Text
    let ratio2 : float = float txtPart2.Text
    let part1  : float  = allocate1 amount ratio1 ratio2
    let part2  : float  = allocate2 amount ratio1 ratio2

    let strPart1 = sprintf "%g" part1
    let strPart2 = sprintf "%g" part2
    txtPart1Value.Text <- strPart1
    txtPart2Value.Text <- strPart2
btnAllocate.Click.Add btnAllocateClick
ratio.Controls.Add btnAllocate

let btnCloseClick e =
    let fileDefault : FileInfo = new FileInfo("default.txt")
    let swDefault : StreamWriter = fileDefault.CreateText()

    try
        swDefault.WriteLine(txtAllocate.Text)
        swDefault.WriteLine(txtPart1.Text)
        swDefault.WriteLine(txtPart2.Text)
        swDefault.WriteLine(txtPart1Value.Text)
        swDefault.WriteLine(txtPart2Value.Text)
    finally
        swDefault.Close()

    ratio.Close()
btnClose.Click.Add btnCloseClick
ratio.Controls.Add btnClose

[<STAThread>]
[<EntryPoint>]
let main argv = 
    Application.Run ratio
    0

Appending Text to a File

You may have created a text-based file and written to it. If you open such a file and find out that a piece of information is missing, you can add that information to the end of the file. To do this, you can call the FileInfo.AppenText() method. Its signature is:

member AppendText : unit -> StreamWriter

When calling this method, you can retrieve the StreamWriter object that it returns, then use that object to add new information to the file.

Reading from a File

As opposed to writing to a file, you can read from it. To support this, the FileInfo class is equipped with a method named OpenText. Its signature is:

member OpenText : unit -> StreamReader

This method returns a StreamReader object from a class of the same name:

type StreamReader =  
    class 
        inherit TextReader 
    end

You can then use this object to read the lines of a text file. Here is an example:

open System
open System.IO
open System.Drawing
open System.Windows.Forms

let allocate1 amount ratio1 ratio2 =
    let totalRatios = ratio1 + ratio2
    let eachPart = amount / totalRatios
    let part1 = eachPart * ratio1
    part1

let allocate2 amount ratio1 ratio2 =
    let totalRatios : float = ratio1 + ratio2
    let eachPart : float    = amount / totalRatios
    let part2 : float       = eachPart * ratio2
    part2

// Form: Ratio
let ratio : Form = new Form(ClientSize = new System.Drawing.Size(268, 178), Text = "Ratio")

// Label: Allocate
ratio.Controls.Add(new Label(AutoSize = true, Location = new Point(22, 19),
                                    Width = 60, Text = "Allocate:"))

// Text Box: Allocate
let txtAllocate : TextBox = new TextBox(Location = new Point(88, 16), Width = 79)
ratio.Controls.Add txtAllocate

// Label: In the ratio
ratio.Controls.Add(new Label(Width = 65, Text = "In the ratio:",
                             AutoSize = true, Location = new Point(22, 54)))

// Text Box: Part1
let txtPart1 : TextBox = new TextBox(Location = new Point(88, 51), Width = 31)
ratio.Controls.Add txtPart1

// Label: Colon
ratio.Controls.Add(new Label(Width = 10, Text = ":",
                             AutoSize = true, Location = new Point(123, 54)))

// Text Box: Part2
let txtPart2 : TextBox = new TextBox(Location = new Point(136, 51), Width = 31)
ratio.Controls.Add txtPart2

// Button: Allocate
let btnAllocate : Button = new Button(Location = new Point(173, 49), Text = "Allocate")

// Label: Line
ratio.Controls.Add(new Label(Size = new System.Drawing.Size(245, 1),
                             Location = new Point(12, 84), BackColor = Color.Black))

// Label: Part 1 Receives
ratio.Controls.Add(new Label(Location = new Point(22, 102),
                             AutoSize = true, Text = "Part 1 Receives:"))

// Text Box: Part 1 Value
let txtPart1Value : TextBox = new TextBox(Location = new Point(114, 99), Width = 53)
ratio.Controls.Add txtPart1Value

// Label: Part 2 Receives
ratio.Controls.Add(new Label(Width =  90, Text = "Part 2 Receives:",
                             AutoSize = true, Location = new Point(22, 138)))

let txtPart2Value : TextBox = new TextBox(Location = new Point(114, 135), Width = 53)
ratio.Controls.Add txtPart2Value

// Button: Close
let btnClose : Button = new Button(Location = new Point(173, 133), Text = "Close")

let RatioLoad e =
    let fileDefault : FileInfo = new FileInfo("default.txt")
    let srDefault : StreamReader = fileDefault.OpenText();

    try
        txtAllocate.Text <- srDefault.ReadLine()
        txtPart1.Text <- srDefault.ReadLine()
        txtPart2.Text <- srDefault.ReadLine()
        txtPart1Value.Text <- srDefault.ReadLine()
        txtPart2Value.Text <- srDefault.ReadLine()
    finally
        srDefault.Close()
ratio.Load.Add RatioLoad

let btnAllocateClick e =
    let amount : float = float txtAllocate.Text
    let ratio1 : float = float txtPart1.Text
    let ratio2 : float = float txtPart2.Text
    let part1  : float  = allocate1 amount ratio1 ratio2
    let part2  : float  = allocate2 amount ratio1 ratio2

    let strPart1 = sprintf "%g" part1
    let strPart2 = sprintf "%g" part2
    txtPart1Value.Text <- strPart1
    txtPart2Value.Text <- strPart2
btnAllocate.Click.Add btnAllocateClick
ratio.Controls.Add btnAllocate

let btnCloseClick e =
    let fileDefault : FileInfo = new FileInfo("default.txt")
    let swDefault : StreamWriter = fileDefault.CreateText()

    try
        swDefault.WriteLine(txtAllocate.Text)
        swDefault.WriteLine(txtPart1.Text)
        swDefault.WriteLine(txtPart2.Text)
        swDefault.WriteLine(txtPart1Value.Text)
        swDefault.WriteLine(txtPart2Value.Text)
    finally
        swDefault.Close();

    ratio.Close()
btnClose.Click.Add btnCloseClick
ratio.Controls.Add btnClose

[<STAThread>]
[<EntryPoint>]
let main argv = 
    Application.Run ratio
    0
 
   
 

Routine Operations on Files

 

Creating a File

The FileInfo constructor is mostly meant only to indicate that you want to use a file, whether it exists already or it would be created. Based on this, if you execute an application that has only a FileInfo object created using the constructor as done above, nothing would happen.

To create a file, you have various alternatives. If you want to create one without writing anything in it, which implies creating an empty file, you can call the FileInfo.Create() method. Its signature is:

member Create : unit -> FileStream

This method simply creates an empty file. Here is an example of calling it:

open System
open System.IO
open System.Windows.Forms

let exercise : Form = new Form(Text = "Exercise")

let flePeople : FileInfo = new FileInfo("People.txt")
flePeople.Create() |> ignore

[<STAThread>]
[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

Opening a File

As opposed to creating a file, probably the second most regular operation performed on a file consists of opening it to read or explore its contents. To support opening a file, the FileInfo class is equipped with the Open() method that is overloaded with three versions. Their signatures are:

member Open : 
        mode:FileMode -> File
Streammember Open : 
        mode:FileMode * 
        access:FileAccess -> FileStream
member Open : 
        mode:FileMode * 
        access:FileAccess * 
        share:FileShare -> FileStream

You can select one of these methods, depending on how you want to open the file, using the options for file mode, file access, and file sharing. Each version of this method returns a FileStream object that you can then use to process the file. After opening the file, you can then read or use its content.

Checking File Existence

When you call the FileInfo.CreateText() method, if the file passed as argument, or as the file in the path of the argument, exists already, it would be deleted and a new one would be created with the same name. This can cause the right file to be deleted. Therefore, before creating a file, you may need to check whether it exists already. To do this, you can check the value of the Boolean FileInfo.Exists property:

abstract Exists : bool with get 
override Exists : bool with get

This property holds a true value if the file exists already and it holds a false value if the file doesn't exist or it doesn't exist in the path. Here is an example:

let RatioLoad e =
    let fileDefault : FileInfo = new FileInfo(@"C:\Resources\default.txt")

    if fileDefault.Exists = true then
        if MessageBox.Show("A default financial allocation exists. Do you want to open it?",
                           "Financial Allocation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes then
            let srDefault : StreamReader = fileDefault.OpenText()

            try
                txtAllocate.Text <- srDefault.ReadLine()
                txtPart1.Text <- srDefault.ReadLine()
                txtPart2.Text <- srDefault.ReadLine()
                txtPart1Value.Text <- srDefault.ReadLine()
                txtPart2Value.Text <- srDefault.ReadLine()
            finally
                srDefault.Close()
ratio.Load.Add RatioLoad

Deleting a File

If you have an existing file you don't need anymore, you can delete it. This operation can be performed by calling the FileInfo.Delete() method. Its signature is:

abstract Delete : unit -> unit  
override Delete : unit -> unit

Here is an example:

open System
open System.IO
open System.Drawing
open System.Windows.Forms

let allocate1 amount ratio1 ratio2 =
    let totalRatios = ratio1 + ratio2
    let eachPart = amount / totalRatios
    let part1 = eachPart * ratio1
    part1

let allocate2 amount ratio1 ratio2 =
    let totalRatios : float = ratio1 + ratio2
    let eachPart : float    = amount / totalRatios
    let part2 : float       = eachPart * ratio2
    part2

// Form: Ratio
let ratio : Form = new Form(MaximizeBox = false, Text = "Ratio",
                            ClientSize = new System.Drawing.Size(268, 178),
                            StartPosition = FormStartPosition.CenterScreen)

// Label: Allocate
ratio.Controls.Add(new Label(AutoSize = true, Location = new Point(22, 19),
                                    Width = 60, Text = "Allocate:"))

// Text Box: Allocate
let txtAllocate : TextBox = new TextBox(Location = new Point(88, 16), Width = 79)
ratio.Controls.Add txtAllocate

// Label: In the ratio
ratio.Controls.Add(new Label(Width = 65, Text = "In the ratio:",
                             AutoSize = true, Location = new Point(22, 54)))

// Text Box: Part1
let txtPart1 : TextBox = new TextBox(Location = new Point(88, 51), Width = 31)
ratio.Controls.Add txtPart1

// Label: Colon
ratio.Controls.Add(new Label(Width = 10, Text = ":",
                             AutoSize = true, Location = new Point(123, 54)))

// Text Box: Part2
let txtPart2 : TextBox = new TextBox(Location = new Point(136, 51), Width = 31)
ratio.Controls.Add txtPart2

// Button: Allocate
let btnAllocate : Button = new Button(Location = new Point(173, 49), Text = "Allocate")

// Label: Line
ratio.Controls.Add(new Label(Size = new System.Drawing.Size(245, 1),
                             Location = new Point(12, 84), BackColor = Color.Black))

// Label: Part 1 Receives
ratio.Controls.Add(new Label(Location = new Point(22, 102),
                             AutoSize = true, Text = "Part 1 Receives:"))

// Text Box: Part 1 Value
let txtPart1Value : TextBox = new TextBox(Location = new Point(114, 99), Width = 53)
ratio.Controls.Add txtPart1Value

// Label: Part 2 Receives
ratio.Controls.Add(new Label(Width =  90, Text = "Part 2 Receives:",
                             AutoSize = true, Location = new Point(22, 138)))

let txtPart2Value : TextBox = new TextBox(Location = new Point(114, 135), Width = 53)
ratio.Controls.Add txtPart2Value

// Button: Close
let btnClose : Button = new Button(Location = new Point(173, 133), Text = "Close")

let RatioLoad e =
    let fileDefault : FileInfo = new FileInfo(@"C:\Resources\default.txt")

    if fileDefault.Exists = true then
        if MessageBox.Show("A default financial allocation exists. Do you want to open it?",
                           "Financial Allocation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes then
            let srDefault : StreamReader = fileDefault.OpenText()

            try
                txtAllocate.Text <- srDefault.ReadLine()
                txtPart1.Text <- srDefault.ReadLine()
                txtPart2.Text <- srDefault.ReadLine()
                txtPart1Value.Text <- srDefault.ReadLine()
                txtPart2Value.Text <- srDefault.ReadLine()
            finally
                srDefault.Close()
        else
            fileDefault.Delete()
ratio.Load.Add RatioLoad

let btnAllocateClick e =
    let amount : float = float txtAllocate.Text
    let ratio1 : float = float txtPart1.Text
    let ratio2 : float = float txtPart2.Text
    let part1  : float  = allocate1 amount ratio1 ratio2
    let part2  : float  = allocate2 amount ratio1 ratio2

    let strPart1 = sprintf "%g" part1
    let strPart2 = sprintf "%g" part2
    txtPart1Value.Text <- strPart1
    txtPart2Value.Text <- strPart2
btnAllocate.Click.Add btnAllocateClick
ratio.Controls.Add btnAllocate

let btnCloseClick e =
    if (String.IsNullOrEmpty(txtAllocate.Text) = false) || 
       (String.IsNullOrEmpty(txtPart1.Text) = false) || 
       (String.IsNullOrEmpty(txtPart2.Text) = false) then
        let fileDefault : FileInfo = new FileInfo(@"C:\Resources\default.txt")
        let swDefault : StreamWriter = fileDefault.CreateText()

        try
            swDefault.WriteLine(txtAllocate.Text)
            swDefault.WriteLine(txtPart1.Text)
            swDefault.WriteLine(txtPart2.Text)
            swDefault.WriteLine(txtPart1Value.Text)
            swDefault.WriteLine(txtPart2Value.Text)
        finally
            swDefault.Close()

    ratio.Close()
btnClose.Click.Add btnCloseClick
ratio.Controls.Add btnClose

[<STAThread>]
[<EntryPoint>]
let main argv = 
    Application.Run ratio
    0

You can perform the same operation using the File class. It is equipped with a method named Delete. Its signature is:

static member Delete : 
        path:string -> unit

When calling this method, pass the name of, or the path (relative or complete) to, the file.

Copying a File

You can make a copy of a file from one directory to another. To do this, you can call the FileInfo.CopyTo() method that is overloaded with two versions. One of the versions has the following signature:

member CopyTo : 
        destFileName:string -> FileInfo

When calling this method, specify the path or directory that will be the destination of the copied file. Here is an example:

open System
open System.IO
open System.Drawing
open System.Windows.Forms

let exercise : Form = new Form(MaximizeBox = false, Text = "Ratio",
                            ClientSize = new System.Drawing.Size(268, 178),
                            StartPosition = FormStartPosition.CenterScreen)

let fleEmployees : FileInfo = new FileInfo("Employees.mpl")
let strMyDocuments : string = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
fleEmployees.CopyTo(String.Concat(strMyDocuments, "\\Federal.txt")) |> ignore

[<STAThread>]
[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

In this example, a file named Employees.mpl in the directory of the project would be retrieved and its content would be applied to a new file named Federal.txt created in the My Documents folder of the current user. When calling the first version of the FileInfo.CopyTo() method, if the file exists already, the operation would not continue and you would simply receive a message box. If you insist, you can overwrite the target file. To do this, you can use the second version of this method. Its signature is:

member CopyTo : 
        destFileName:string * 
        overwrite:bool -> FileInfo

The first argument is the same as that of the first version of the method. The second argument specifies what action to take if the file exists already in the target directory. If you want to overwrite it, pass the second argument as true; otherwise, pass it as false.

You can also copy a file using the File class that is equipped with an overloaded method named Copy. One of its signatures is:

static member Copy : 
        sourceFileName:string * 
        destFileName:string -> unit

Here is an example of calling this method:

open System
open System.IO
open System.Drawing
open System.Windows.Forms

let exercise : Form = new Form(MaximizeBox = false, Text = "Exercise",
                            ClientSize = new System.Drawing.Size(268, 178),
                            StartPosition = FormStartPosition.CenterScreen)

let strMyDocuments : string = Environment.GetFolderPath(Environment.SpecialFolder.Personal)

File.Copy(@"C:\Resources\Employees.txt", strMyDocuments + "\\Staff Members.txt")

[<STAThread>]
[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

Another version of the method uses the following signature:

static member Copy :
        sourceFileName:string *
        destFileName:string *
        overwrite:bool -> unit

Remember that  you can copy a file in the same directory or to a different folder.

Moving a File

If you copy a file from one directory to another, you would have two copies of the same file or the same contents in two files. Instead of copying, if you want, you can move a file from one directory to another. This operation can be performed by calling the FileInfo.MoveTo() method. Its signature is:

member MoveTo : 
        destFileName:string -> unit

The argument to this method is the same as that of the CopyTo() method. After executing this method, the FileInfo object would be moved to the destFileName path. Here is an example:

open System
open System.IO
open System.Drawing
open System.Windows.Forms

let exercise : Form = new Form(MaximizeBox = false, Text = "Exercise",
                               ClientSize = new System.Drawing.Size(268, 178),
                               StartPosition = FormStartPosition.CenterScreen)

let fleContractors : FileInfo = new FileInfo(@"C:\Exercises01\Contractors.txt")
let strMyDocuments : string = Environment.GetFolderPath(Environment.SpecialFolder.Personal)

fleContractors.MoveTo(strMyDocuments + "\\Contractors.txt")

[<STAThread>]
[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

Renaming a File

If you have an existing file whose name you don't want anymore, you can rename it. To support this operation, you can call the MoveTo() method of the FileInfo class. Here is an example:

open System
open System.IO
open System.Drawing
open System.Windows.Forms

let exercise : Form = new Form(MaximizeBox = false, Text = "Exercise",
                            ClientSize = new System.Drawing.Size(268, 178),
                            StartPosition = FormStartPosition.CenterScreen)

let strMyDocuments : string = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
let fleEmployees : FileInfo = new FileInfo(strMyDocuments + "\\Employees.txt")

fleEmployees.MoveTo(strMyDocuments + "\\Seasonals.txt")

[<STAThread>]
[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

To perform the same operation, the File class provides a method named Move. Its signature is:

static member Move : 
        sourceFileName:string * 
        destFileName:string -> unit

Here is an example:

File.Move(@"C:\Exercise\Soho.txt", @"C:\Exercise\Whatever.txt")

Characteristics of a File

 

The Date and Time a File Was Created 

After a file has been created, the operating system makes a note of the date and the time the file was created. This information can be valuable in other operations such as search routines. You too are allowed to change this date and time values to those you prefer.

As mentioned already, the OS makes sure to keep track of the date and time a file was created. To find out what those date and time values are, you can access the get accessor of the FileSystemInfo.CreationTime property, which is of type DateTime:

member CreationTime : DateTime with get, set

Here is an example of using it:

open System
open System.IO
open System.Drawing
open System.Windows.Forms

let exercise : Form = new Form(MaximizeBox = false, Text = "Exercise",
                            ClientSize = new System.Drawing.Size(268, 178),
                            StartPosition = FormStartPosition.CenterScreen)

let strMyDocuments : string = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
let fleEmployees : FileInfo = new FileInfo(strMyDocuments + "\\Contractors.txt")

let dteCreationTime : DateTime = fleEmployees.CreationTime

exercise.Text <- dteCreationTime.ToShortDateString()

[<STAThread>]
[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

Of course, you can get only either the date or only the time. If you don't like the date, the time, or both, that the OS would have set when the file was created, you can change them. To change one or both of these values, you can assign a desired DateTime object to the set accessor of the FileSystemInfo.CreationTime property.

The Date and Time a File Was Last Accessed 

Many applications allow a user to open an existing file and to modify it. When people work in a team or when a particular file is regularly opened, at one particular time, you may want to know the date and time that the file was last accessed. To get this information, you can access the FileSystemInfo.LastAccessTime property, which is of type DateTime:

member LastAccessTime : DateTime with get, set

If you are interested to know the last date and time a file was modified, you can get the value of its FileSystemInfo.LastWriteTime property, which is of type DateTime:

member LastWriteTime : DateTime with get, set

The Name of a File

The operating system requires that each file have a name. In fact, the name must be specified when creating a file. This allows the OS to catalogue the computer files. This also allows you to locate or identify a particular file you need.

When reviewing or opening a file, to get its name, the FileInfo class is equipped with the Name property:

abstract Name : string with get 
override Name : string with get

Here is an example:

open System
open System.IO
open System.Drawing
open System.Windows.Forms

let exercise : Form = new Form(MaximizeBox = false, Text = "Exercise",
                            ClientSize = new System.Drawing.Size(268, 178),
                            StartPosition = FormStartPosition.CenterScreen)

let strMyDocuments : string = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
let fleEmployees : FileInfo = new FileInfo(strMyDocuments + "\\Contractors.txt")

exercise.Text <- fleEmployees.Name

[<STAThread>]
[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This string simply identifies a file.

The Extension of a File

Some applications allow the user to choose among various extensions. For example, using Notepad, a user can open a text, a PHP, a script, or an HTML file. When you access a file or when the user opens one, to know the extension of the file, you can access the value of the FileSystemInfo.Extension property:

member Extension : string with get

Here is an example:

open System
open System.IO
open System.Drawing
open System.Windows.Forms

let exercise : Form = new Form(MaximizeBox = false, Text = "Exercise",
                            ClientSize = new System.Drawing.Size(268, 178),
                            StartPosition = FormStartPosition.CenterScreen)

let strMyDocuments : string = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
let fleEmployees : FileInfo = new FileInfo(strMyDocuments + "\\Contractors.txt")

exercise.Text <- fleEmployees.Extension


[<STAThread>]
[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

The Size of a File

One of the routine operations the operating system performs consists of calculating the size of files it holds. This information is provided in terms of bits, kilobits, or kilobytes. To get the size of a file, the FileInfo class is quipped with the Length property:

member Length : int64 with get

Here is an example of accessing it:

open System
open System.IO
open System.Drawing
open System.Windows.Forms

let exercise : Form = new Form(MaximizeBox = false, Text = "Exercise",
                            ClientSize = new System.Drawing.Size(268, 178),
                            StartPosition = FormStartPosition.CenterScreen)

let strMyDocuments : string = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
let fleEmployees : FileInfo = new FileInfo(strMyDocuments + "\\Contractors.txt")

exercise.Text <- sprintf "%i bytes" fleEmployees.Length

[<STAThread>]
[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

The Path to a File

Besides its name, a file must be located somewhere. The location of a file is referred to as its path or directory. The FileInfo class represents this path as the DirectoryName property:

member DirectoryName : string with get

Therefore, if a file has already been created, to get its path, you can access the value of the FileInfo.DirectoryName property. Besides the FileInfo.Directoryname, to know the full path to a file, you can access its FileSystemInfo.FullName property:

abstract FullName : string with get 
override FullName : string with get

The Attributes of a File

Attributes are characteristics that apply to a file, defining what can be done or must be disallowed on it. The attributes are primarily defined by, and in, the operating system, mostly when a file is created. When the user accesses or opens a file, to get its attributes, you can access the value of its FileSystemInfo.Attributes property. This property produces a FileAttributes object:

member Attributes : FileAttributes with get, set

When you create or access a file, you can specify or change some of the attributes. To do this, you can create a FileAttributes object and assign it to the FileSystemInfo.Attributes property.

FileAttributes is an enumeration with the following members: Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContentIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary.

 
 
   
 

Home Copyright © 2015, FunctionX Home