How To: Create A File - Visual Basic | Microsoft Learn

Table of contents Exit editor mode Ask Learn Ask Learn Focus mode Table of contents Read in English Add Add to plan Edit

Share via

Facebook x.com LinkedIn Email Copy Markdown Print

Note

Access to this page requires authorization. You can try signing in or changing directories.

Access to this page requires authorization. You can try changing directories.

How to: Create a File in Visual Basic Feedback Summarize this article for me

In this article

This example creates an empty text file at the specified path using the Create method in the File class.

Example

Imports System.IO Imports System.Text Module Module1 Sub Main() Dim path As String = "c:\temp\MyTest.txt" ' Create or overwrite the file. Dim fs As FileStream = File.Create(path) ' Add text to the file. Dim info As Byte() = New UTF8Encoding(True).GetBytes("This is some text in the file.") fs.Write(info, 0, info.Length) fs.Close() End Sub End Module

Compiling the Code

Use the file variable to write to the file.

Robust Programming

If the file already exists, it is replaced.

The following conditions may cause an exception:

  • The path name is malformed. For example, it contains illegal characters or is only white space (ArgumentException).

  • The path is read-only (IOException).

  • The path name is Nothing (ArgumentNullException).

  • The path name is too long (PathTooLongException).

  • The path is invalid (DirectoryNotFoundException).

  • The path is only a colon ":" (NotSupportedException).

.NET Framework Security

A SecurityException may be thrown in partial-trust environments.

The call to the Create method requires FileIOPermission.

An UnauthorizedAccessException is thrown if the user does not have permission to create the file.

See also

  • System.IO
  • Create
Collaborate with us on GitHub The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.

.NET

Open a documentation issue Provide product feedback

Feedback

Was this page helpful?

Yes No No

Need help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Ask Learn Ask Learn Suggest a fix?
  • Last updated on 2022-05-26

In this article

Was this page helpful?

Yes No No

Need help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Ask Learn Ask Learn Suggest a fix?

Tag » How To Create A Text File