Como gravar texto em arquivos no diretório Meus Documentos no Visual BasicHow to: Write Text to Files in the My Documents Directory in Visual Basic
O objeto My.Computer.FileSystem.SpecialDirectories
permite que você acesse diretórios especiais, como o diretório MyDocuments.The My.Computer.FileSystem.SpecialDirectories
object allows you to access special directories, such as the MyDocuments directory.
ProcedimentoProcedure
Para gravar novos arquivos de texto no diretório Meus DocumentosTo write new text files in the My Documents directory
Use a propriedade
My.Computer.FileSystem.SpecialDirectories.MyDocuments
para fornecer o caminho.Use theMy.Computer.FileSystem.SpecialDirectories.MyDocuments
property to supply the path.Dim filePath As String filePath = System.IO.Path.Combine( My.Computer.FileSystem.SpecialDirectories.MyDocuments, "test.txt")
Use o método
WriteAllText
para escrever o texto no arquivo especificado.Use theWriteAllText
method to write text to the specified file.My.Computer.FileSystem.WriteAllText(filePath, "some text", True)
ExemploExample
Try
Dim filePath As String
filePath = System.IO.Path.Combine(
My.Computer.FileSystem.SpecialDirectories.MyDocuments, "test.txt")
My.Computer.FileSystem.WriteAllText(filePath, "some text", False)
Catch fileException As Exception
Throw fileException
End Try
Compilando o códigoCompiling the Code
Substitua test.txt
pelo nome do arquivo no qual você deseja gravar.Replace test.txt
with the name of the file you want to write to.
Programação robustaRobust Programming
Esse código lança novamente todas as exceções que podem ocorrer ao gravar texto no arquivo.This code rethrows all the exceptions that may occur when writing text to the file. É possível reduzir a probabilidade de exceções usando controles do Windows Forms como os componentes OpenFileDialogSaveFileDialog que limitam as escolhas do usuário para validar nomes de arquivo.You can reduce the likelihood of exceptions by using Windows Forms controls such as the OpenFileDialog and the SaveFileDialog components that limit the user choices to valid file names. No entanto, o uso desses controles não é à prova de falhas.Using these controls is not foolproof, however. O sistema de arquivos pode ser alterado entre o momento em que o usuário seleciona um arquivo e o momento em que o código é executado.The file system can change between the time the user selects a file and the time that the code executes. Portanto, o tratamento de exceções é quase sempre é necessário ao trabalhar com arquivos.Exception handling is therefore nearly always necessary when with working with files.
Segurança do .NET Framework.NET Framework Security
Se você estiver executando em um contexto de confiança parcial, o código pode gerar uma exceção devido a privilégios insuficientes.If you are running in a partial-trust context, the code might throw an exception due to insufficient privileges. Para obter mais informações, consulte Noções Básicas da Segurança de Acesso do Código.For more information, see Code Access Security Basics.
Esse exemplo cria um novo arquivo.This example creates a new file. Se um aplicativo precisar criar um arquivo, esse aplicativo precisará da permissão de criação para a pasta.If an application needs to create a file, that application needs Create permission for the folder. As permissões são definidas usando listas de controle de acesso.Permissions are set using access control lists. Se o arquivo já existir, o aplicativo precisará somente da permissão de gravação, um privilégio menor.If the file already exists, the application needs only Write permission, a lesser privilege. Sempre que possível, é mais seguro criar o arquivo durante a implantação e somente conceder privilégios de leitura para um único arquivo, em vez de conceder privilégios de criação para uma pasta.Where possible, it is more secure to create the file during deployment, and only grant Read privileges to a single file, rather than to grant Create privileges for a folder. Além disso, é mais seguro gravar dados em pastas de usuário do que na pasta raiz ou na pasta Arquivos de Programas.Also, it is more secure to write data to user folders than to the root folder or the Program Files folder. Para obter mais informações, consulte Visão Geral da Tecnologia de ACL.For more information, see ACL Technology Overview.