2

ファイルが存在するかどうかを確認しようとしていますが、存在する場合は何もしません。ファイルが存在しない場合は、テキストファイルを作成します。次に、そのファイルにテキストを書き込みます。このコードのどこが間違っているのですか?テキストファイルに複数行を書き込もうとしていますが、その部分が機能していません。テキストファイルを作成しています...書き込みを行っていないだけです。

Dim file As System.IO.FileStream
 Try
  ' Indicate whether the text file exists
  If My.Computer.FileSystem.FileExists("c:\directory\textfile.txt") Then
    Return
  End If

  ' Try to create the text file with all the info in it
  file = System.IO.File.Create("c:\directory\textfile.txt")

  Dim addInfo As New System.IO.StreamWriter("c:\directory\textfile.txt")

  addInfo.WriteLine("first line of text")
  addInfo.WriteLine("") ' blank line of text
  addInfo.WriteLine("3rd line of some text")
  addInfo.WriteLine("4th line of some text")
  addInfo.WriteLine("5th line of some text")
  addInfo.close()
 End Try
4

3 に答える 3

11

このファイルで割り当てたリソースを適切に解放していないようです。

常にリソースをUsingステートメントでラップIDisposableして、リソースの操作が終了したらすぐにすべてのリソースが適切に解放されるようにしてください。

' Indicate whether the text file exists
If System.IO.File.exists("c:\directory\textfile.txt") Then
    Return
End If

Using Dim addInfo = File.CreateText("c:\directory\textfile.txt")
    addInfo.WriteLine("first line of text")
    addInfo.WriteLine("") ' blank line of text
    addInfo.WriteLine("3rd line of some text")
    addInfo.WriteLine("4th line of some text")
    addInfo.WriteLine("5th line of some text")
End Using

しかし、あなたの場合、このFile.WriteAllLines方法を使用する方が適切と思われます。

' Indicate whether the text file exists
If System.IO.File.exists("c:\directory\textfile.txt") Then
    Return
End If

Dim data As String() = {"first line of text", "", "3rd line of some text", "4th line of some text", "5th line of some text"}
File.WriteAllLines("c:\directory\textfile.txt", data)
于 2013-02-15T22:01:22.513 に答える
1

それはすべてうまくいきます!-これはファイルを作成して書き込むための最良の方法ではありません-書きたいテキストを作成してから新しいファイルに書き込むだけですが、コードを考えると、不足しているのは書き込む前にファイルを作成しました。この行を変更するだけです:

file = System.IO.File.Create("c:\directory\textfile.txt")

に:

file = System.IO.File.Create("c:\directory\textfile.txt")
file.close

残りはすべて機能します。

于 2013-02-15T22:01:44.853 に答える
1
 file = System.IO.File.Create("path")

作成したファイルを閉じて、書き込みを試みます。

 file.Close()
     Dim addInfo As New System.IO.StreamWriter("path")
于 2016-11-18T12:20:10.197 に答える