vb.net 如何在我的项目根目录中创建文件夹和文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18229973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:40:07  来源:igfitidea点击:

How to create a folder and a file in my project root directory

vb.netfiledirectoryrelative-path

提问by Sudha

I have a vb .net application which is stored in my D: drive. I need to create a folder and a file in my project root directory. I used the following code to create the folder as well as the file.

我有一个 vb .net 应用程序,它存储在我的 D: 驱动器中。我需要在我的项目根目录中创建一个文件夹和一个文件。我使用以下代码来创建文件夹和文件。

 If (Not System.IO.Directory.Exists("\test\")) Then
                System.IO.Directory.CreateDirectory("\test\")
                If (Not System.IO.File.Exists("\test\output.txt")) Then
                    System.IO.File.Create("\test\output.txt")
                End If
            End If

But the folder and the file is created in C: drive. I used Dim fullpath As String = Path.GetFullPath("\test\output.txt")to identify where the file and folder is created.

但是文件夹和文件是在 C: 驱动器中创建的。我曾经Dim fullpath As String = Path.GetFullPath("\test\output.txt")确定文件和文件夹的创建位置。

I want to create it in my project root directory. That means I need to create the folder using a relative path criteria.

我想在我的项目根目录中创建它。这意味着我需要使用相对路径标准创建文件夹。

回答by SoftwareCarpenter

If you want the directory of the executable or dll of your running application then:

如果您想要正在运行的应用程序的可执行文件或 dll 的目录,则:

   Dim spath As String
        spath = System.IO.Path.GetDirectoryName( _
                   System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
        If (Not System.IO.Directory.Exists(Path.Combine(spath, "test"))) Then

            System.IO.Directory.CreateDirectory(Path.Combine(spath, "test"))

            If (Not System.IO.File.Exists(Path.Combine(spath, "test\output.txt"))) Then

                System.IO.File.Create(Path.Combine(spath, "test\output.txt"))
            End If
        End If

If you want the solution/project directory then:

如果您想要解决方案/项目目录,则:



        Dim spath As String = Directory.GetCurrentDirectory

        If (Not System.IO.Directory.Exists(Path.Combine(spath, "test"))) Then
            System.IO.Directory.CreateDirectory(Path.Combine(spath, "test"))
            If (Not System.IO.File.Exists(Path.Combine(spath, "test\output.txt"))) Then
                System.IO.File.Create(Path.Combine(spath, "test\output.txt"))
            End If
        End If

回答by Lectere

You could use this path, and work from there...

您可以使用此路径,然后从那里开始工作...

    MsgBox(Application.StartupPath)