如何创建和打开文件文档

时间:2017-08-29 05:31:39

标签: .net vb.net file console-application

我有以下方法/程序

Private Sub CreateFile(ByVal filename As String, ByVal directory As String, ByVal extension As String)

    Dim file2create = directory & filename & extension
    Console.WriteLine(file2create)
    If (Not File.Exists(file2create)) Then
        File.Create(file2create)
    Else
        File.Open(file2create, FileMode.Open)
    End If
    console.ReadLine()
End Sub

此代码成功创建了一个文件,但无法打开它,只是说,我已经检查过类似问题的其他答案,但是说答案没有解决我的问题,我是什么意思在这里做错了。感谢

================================ UPDATE ============== ======================

感谢答案的人,但文件没有打开。只是为了澄清,当我说开放时,我的意思是同样的行为是实际进入文件并单击它。

如果我要使用此question

中的代码
   Private Function ShellExecute(ByVal File As String) As Boolean

      Dim myProcess As New Process
      myProcess.StartInfo.FileName = File
      myProcess.StartInfo.UseShellExecute = True
      myProcess.StartInfo.RedirectStandardOutput = False
      myProcess.Start()
      myProcess.Dispose()

    End Function

文件会成功打开,但如果我要使用file.open(),文件将无法打开,所以从本质上讲,我希望创建然后以与上述代码相同的方式打开文件确实

2 个答案:

答案 0 :(得分:3)

如果文件不存在,这是创建文件的正确方法,然后使用File.Open方法打开它,该方法返回FileStream对象:

Private Sub OpenOrCreateFile(ByVal filename As String, ByVal directory As String, ByVal extension As String)
    'Use `Path.Combine` so you don't have to worry if the
    'directory path ends with a "\" or not.
    Dim file2create = Path.Combine(directory, filename) & extension
    Console.WriteLine(file2create)

    'Use a `Using` statement to make sure the FileStream object gets
    'disposed, and to prevent the file from staying locked after
    'finishing what you want to do with it.
    Using fs As FileStream = File.Open(file2create, FileMode.OpenOrCreate)
        'I'm not sure what you'd like to do after opening the file,
        'but now you have a `FileStream` object which you can use
        'to write bytes to the file (i.e. using `fs.Write()`).
    End Using

    Console.ReadLine()
End Sub

如果您只是想创建一个文件,并为其写一些文本覆盖现有内容,您可以使用:

File.WriteAllText(file2create, "SomethingToWrite")

希望有所帮助。

答案 1 :(得分:1)

您必须在InitializeStorageAccount阻止后移动File.Open

下面:

IF..Then