Windows create text file

File. Create Text(String) Метод

Определение

Создается или открывается файл для записи текста в кодировке UTF-8. Creates or opens a file for writing UTF-8 encoded text. Если файл уже существует, его содержимое перезаписывается. If the file already exists, its contents are overwritten.

Параметры

Файл, который нужно открыть для записи. The file to be opened for writing.

Возвращаемое значение

StreamWriter, выполняющий запись в указанный файл в кодировке UTF-8. A StreamWriter that writes to the specified file using UTF-8 encoding.

Исключения

У вызывающего объекта отсутствует необходимое разрешение. The caller does not have the required permission.

-или- -or- Параметр path указывает файл, доступный только для чтения. path specified a file that is read-only.

-или- -or- path указывает файл, который скрыт. path specified a file that is hidden.

path представляет собой строку нулевой длины, содержащую только пробелы или один или несколько недопустимых символов, заданных методом InvalidPathChars. path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

path имеет значение null . path is null .

Указанный путь, имя файла или оба значения превышают максимальную длину, заданную в системе. The specified path, file name, or both exceed the system-defined maximum length.

Указан недопустимый путь (например, он ведет на несопоставленный диск). The specified path is invalid (for example, it is on an unmapped drive).

Параметр path задан в недопустимом формате. path is in an invalid format.

Примеры

В следующем примере создается файл для записи и чтения текста. The following example creates a file for text writing and reading.

Комментарии

Этот метод эквивалентен StreamWriter(String, Boolean) перегрузке конструктора с append параметром, для которого задано значение false . This method is equivalent to the StreamWriter(String, Boolean) constructor overload with the append parameter set to false . Если файл, указанный параметром path , не существует, он будет создан. If the file specified by path does not exist, it is created. Если файл существует, его содержимое перезаписывается. If the file does exist, its contents are overwritten. Дополнительные потоки могут считывать файл, пока он открыт. Additional threads are permitted to read the file while it is open.

path Параметр может указывать сведения относительного или абсолютного пути. The path parameter is permitted to specify relative or absolute path information. Сведения об относительном пути интерпретируется как относительно текущего рабочего каталога. Relative path information is interpreted as relative to the current working directory. Сведения о получении текущего рабочего каталога см. в разделе GetCurrentDirectory . To obtain the current working directory, see GetCurrentDirectory.

Читайте также:  Ssd медленная загрузка windows

Список общих задач ввода-вывода см. в разделе Общие задачи ввода-вывода. For a list of common I/O tasks, see Common I/O Tasks.

FileSystemObject object

Provides access to a computer’s file system.

Syntax

Scripting.FileSystemObject

Remarks

The following code illustrates how the FileSystemObject object is used to return a TextStream object that can be read from or written to:

In the example code:

  • The CreateObject function returns the FileSystemObject ( fs ).
  • The CreateTextFile method creates the file as a TextStream object ( a ).
  • The WriteLine method writes a line of text to the created text file.
  • The Close method flushes the buffer and closes the file.

Methods

Method Description
BuildPath Appends a name to an existing path.
CopyFile Copies one or more files from one location to another.
CopyFolder Copies one or more folders from one location to another.
CreateFolder Creates a new folder.
CreateTextFile Creates a text file and returns a TextStream object that can be used to read from, or write to the file.
DeleteFile Deletes one or more specified files.
DeleteFolder Deletes one or more specified folders.
DriveExists Checks if a specified drive exists.
FileExists Checks if a specified file exists.
FolderExists Checks if a specified folder exists.
GetAbsolutePathName Returns the complete path from the root of the drive for the specified path.
GetBaseName Returns the base name of a specified file or folder.
GetDrive Returns a Drive object corresponding to the drive in a specified path.
GetDriveName Returns the drive name of a specified path.
GetExtensionName Returns the file extension name for the last component in a specified path.
GetFile Returns a File object for a specified path.
GetFileName Returns the file name or folder name for the last component in a specified path.
GetFolder Returns a Folder object for a specified path.
GetParentFolderName Returns the name of the parent folder of the last component in a specified path.
GetSpecialFolder Returns the path to some of Windows’ special folders.
GetTempName Returns a randomly generated temporary file or folder.
Move Moves a specified file or folder from one location to another.
MoveFile Moves one or more files from one location to another.
MoveFolder Moves one or more folders from one location to another.
OpenAsTextStream Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.
OpenTextFile Opens a file and returns a TextStream object that can be used to access the file.
WriteLine Writes a specified string and new-line character to a TextStream file.

Properties

Property Description
Drives Returns a collection of all Drive objects on the computer.
Name Sets or returns the name of a specified file or folder.
Path Returns the path for a specified file, folder, or drive.
Size For files, returns the size, in bytes, of the specified file; for folders, returns the size, in bytes, of all files and subfolders contained in the folder.
Type Returns information about the type of a file or folder (for example, for files ending in .TXT, «Text Document» is returned).

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Объект FileSystemObject метод CreateTextFile — Как создать текстовый файл

Всем привет, с вами автор блога scriptcoding.ru. В этой статье мы подробно рассмотрим метод объекта FileSystemObject (fso) CreateTextFile, который показывает, как создавать текстовый файл. Метод CreateTextFile fso объекта позволяет получить доступ к другому объекту – TextStream, который в свою очередь отвечает за чтение и запись данных в созданный текстовый файл.

Прежде всего нужно сделать небольшое лирическое отступление… Смотрите, как создать текстовый файл рядовыми методами без программирования? В голову сразу приходит текстовый редактор Блокнот. Как и с любым каталогом, создать текстовый файл можно всего в два этапа: щелкаем правой кнопкой мыши по пустому месту на диске или в директории, далее из контекстного меню выбираем пункт «Создать/Текстовый документ«, далее просто задаем имя файла и все. Но, в большинстве случаев достаточно открыть программу Блокнот и уже оттуда сохранить текстовый файл в нужном месте.

Хорошо, теперь можно приступить к программированию, но сначала, давайте рассмотрим параметры метода CreateTextFile, который и показывает как создать текстовый файл:

CreateTextFile (Filename [,Overwrite[, Unicode]]) – Видим, что метод принимает три параметра, только первый параметр является обязательным.

  • Filename – Данный параметр содержит строку, которая определяет путь и имя для создаваемого текстового файла. Если указать только имя файла, то он будет создан в текущем каталоге (каталог, из которого произведен запуск сценария)
  • Overwrite – Параметр является необязательным. Может принимать логическое true – перезаписать файл, если он уже существует или false – возможность перезаписи отсутствует. По умолчанию, стоит значение false.
  • Unicode – Данный параметр не является обязательным, он определяет кодировку создаваемого текстового файла. Может принимать логическое значение true – формат Unicode или false – формат ASCII .

Хорошо, теперь можно приступить к программированию, но сначала небольшое пояснение.

Используя метод fso CreateTextFile, мы создаем не просто текстовый файл с данными, а произведем запись в поток. Поток – данное выражение присуще только файловой системе NTFS. Суть заключается в том, что к любому документу или даже диску можно привязать один или несколько потоков. Как создать новый текстовый файл. Например, идёт имя файла, двоеточие, имя потока. Поток, содержит имя и расширение.

Для эксперимента, откройте командную строку и пропишите следующий код:

В данном случае, к файлу new.txt будет привязан поток potok.txt и в него будет записана строка «Hello, word«. Вы увидите, что документ содержит нулевой размер, и при попытке открыть его с помощью простого блокнота вы ничего не увидите. Для этого в окне «Пуск/Выполнить» нужно прописать:

Что то подобное мы сделаем с помощью сценариев.

Для начала создадим сценарий createtextfile vbs и пропишем в нем следующие строки кода:

Тут стоит обратить внимание на следующую особенность, если мы попытаемся с помощью функции OpenTextFile открыть документ my_file.txt, не прописав после него через двоеточие имя потока, то получим ошибку:

Ввод данных за пределами файла

Видимо, сервер Windows Script Host умеет определять, что в документе содержится скрытая информация. Также, вы заметили, что вместо функции MsgBox для вывода данных я использовал стандартную WScript.Echo . Не знаю почему, но MsgBox выводит только часть данных. Также, в данном примере я использовал собственную функцию CreateObject языка VBScript, а для освобождения ссылки на объект применил ключевое слово nothing .

А вот аналогичный сценарий createtextfile vbs, но уже на языке jscript:

В этом примере, мы просто привязали еще один поток к файлу. Фактически, один поток будет содержать содержимое скрипта на языке vbscript (createtextfile vbs), а другой – содержимое на языке jscript (createtextfile js).

И так, мы рассмотрели как создать текстовый файл программным путем с помощью метода CreateTextFile и с помощью стандартных средств Windows.

Спасибо за внимание. Автор блога Владимир Баталий

CreateTextFile method

Creates a specified file name and returns a TextStream object that can be used to read from or write to the file.

Syntax

object.CreateTextFile (filename, [ overwrite, [ unicode ]])

The CreateTextFile method has these parts:

Part Description
object Required. Always the name of a FileSystemObject or Folder object.
filename Required. String expression that identifies the file to create.
overwrite Optional. Boolean value that indicates if an existing file can be overwritten. The value is True if the file can be overwritten; False if it can’t be overwritten. If omitted, existing files can be overwritten.
unicode Optional. Boolean value that indicates whether the file is created as a Unicode or ASCII file. The value is True if the file is created as a Unicode file; False if it’s created as an ASCII file. If omitted, an ASCII file is assumed.

Remarks

The following code illustrates how to use the CreateTextFile method to create and open a text file. If the overwrite argument is False, or is not provided, for a filename that already exists, an error occurs.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Читайте также:  Windows 10 убедитесь что имя домена введено правильно
Оцените статью