Quantcast
Channel: VBForums - Visual Basic .NET
Viewing all articles
Browse latest Browse all 27349

Make a file in a directory, and write to it.

$
0
0
The problem I am having is that when I use FileSystem.CreateDirectory it creates a directory but not a file in that directory in which to accept data. As commented, if my variable filePath is input with something like: C:\newfile.txt, the data is written to to that file just fine. However, if the file path is input as c:\newfolder\newfile.txt or c:\newfolder\newfile the folders are made, (in the instance of the first example, newfile.txt is created as a folder (instead of a file) un the folder, "newfolder". In either case, the program stops with an exception.
Therefore, it is evident to me that " My.Computer.FileSystem.CreateDirectory(filePath)" only creates folders despite the path including a file in the program.

vb Code:
  1. '*********************************************************
  2. Public Sub ToFile(ByVal StrPadding As Integer())
  3.         Dim i As Integer
  4.         'Creates dirctory.
  5.         My.Computer.FileSystem.CreateDirectory(filePath)
  6.  
  7.         'writes text to file (only if file is located in the root).
  8.         For i = 0 To 9
  9.             My.Computer.FileSystem.WriteAllText(filePath, CStr(StrPadding(i)), True)
  10.         Next
  11.     End Sub
  12. '**********************************************************
There is another method (from documentation) using FileStream instead of FileSystem that seems to create a path and a file:

vb Code:
  1. Imports System
  2. Imports System.IO
  3. Imports System.Text
  4.  
  5. Module Module1
  6.  
  7.     Sub Main()
  8.         Dim path As String = "c:\temp\MyTest.txt"
  9.         ' Create or overwrite the file.
  10.         Dim fs As FileStream = File.Create(path)
  11.         ' Add text to the file.
  12.         Dim info As Byte() = New UTF8Encoding(True).GetBytes("This is some text in the file.")
  13.         fs.Write(info, 0, info.Length)
  14.         fs.Close()
  15.     End Sub
  16. End Module
But I need help with meshing the two systems (if there is not a seperate way creating a file using a single varible combining the path and file name, using Filesystem), while not having to give up my For-Next loop to write the data to the file. Any suggestions for some elegant programming that does not require I abandon my existing For-Next loop?

Viewing all articles
Browse latest Browse all 27349

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>