File: Create

Create

Creates or overwrites the specified file.



 Public Function Create(
	  ByRef Path As String,
	  Optional ByVal BufferSize As Long = 4096 ) As FileStream

Parameters

Path
[ByRef] String. The name of the file.
BufferSize
[ByVal] Optional. Long. The number of bytes buffered for reads and writes to the file.  

Default: 4096

Return Values

FileStream -  A FileStream with the specified buffer size that provides read/write access to the file specified in Path.

Remarks

The FileStream object created by this method has a default FileShare value of None; no other process or code can access the created file until the original file handle is closed.

The Path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.

This method is equivalent to the NewFileStream(String, FileMode, FileAccess, FileShare, Int32) constructor. If the specified file does not exist, it is created; if it does exist and it is not read-only, the contents are overwritten.

By default, full read/write access to new files is granted to all users. The file is opened with read/write access and must be closed before it can be opened by another application.

Exceptions

ExceptionCondition
ArgumentException Path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by GetInvalidPathChars.
PathTooLongException The specified path, file name, or both exceed the system-defined maximum length. On Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
DirectoryNotFoundException The specified path is invalid (for example, it is on an unmapped drive).
NotSupportedException Path is in an invalid format.

Examples

The following example creates a file with the specified buffer size.

Public Sub Main()
    Const Path As String = "c:\temp\MyTest.txt"

    ' Delete the file if it exists.
    If File.Exists(Path) Then
        File.Delete Path
    End If

    ' Create the file.
    Dim fs As FileStream
    Dim Info() As Byte

    Set fs = File.Create(Path, 1024)
    Info = NewUTF8Encoding(True).GetBytes("This is some text in the file.")
    
    ' Add some information to the file.
    fs.WriteBlock Info, 0, CorArray.Length(Info)
    fs.CloseStream

    ' Open the stream and read it back.
    Dim sr As StreamReader
    Set sr = File.OpenText(Path)
    
    Do While sr.Peek() >= 0
        Debug.Print sr.ReadLine
    Loop
    
    sr.CloseReader
End Sub

See Also

Project CorLib Overview

Class File Overview