【问题标题】:Start in folder with dot.net execution (batch file)从带有 dot.net 执行的文件夹开始(批处理文件)
【发布时间】:2021-08-10 04:22:50
【问题描述】:

我想执行以下操作,但我希望能够将应用程序移动到任何位置,并且文件 client_secrets.json 将始终位于同一文件夹中。该语句应从根 (d:) 调用。有没有办法在(工作)文件夹中指定开始?

d:\> dotnet D:\projects\Test\Test.GoogleSheets\bin\Debug\netcoreapp3.1\Test.GoogleSheets.dll
Unhandled exception. System.IO.FileNotFoundException: Could not find file 'D:\client_secret.json'.
File name: 'D:\client_secret.json'
   at System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)
   at System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
   at Test.GoogleSheets.Program.Main(String[] args) in D:\projects\Test\Test.GoogleSheets\Program.cs:line 33

【问题讨论】:

    标签: c# batch-file cmd


    【解决方案1】:

    FileStream等东西的默认目录是当前工作目录(.exe.dll所在的目录)

    这种工作方式是在 C# 中,程序使用两种路径作为参数,例如 FileStream 的参数。

    There are Absolute paths and Relative paths

    绝对路径
    这些路径完全指定了一个位置:无论当前位置如何,文件或目录都可以唯一标识。

    绝对路径的一个例子是

    'D:\client_secret.json'
    

    相对路径
    这些路径指定了部分位置:当前位置用作起点,当定位使用相对路径指定的文件时。

    一个例子是

    /Data/game_data.bin
    

    在上面的示例中,我们将使用Data 文件夹中的game_data.bin 文件。 Data 文件夹将与 .exe(或 .dll)位于同一目录中

    或者说我们想引用我们上方文件夹中的文件。我们可以使用../ 文件路径来表示“这是我上面的东西”。

    ../../Readme.md
    

    这将是位于我们的.exe/.dll)父文件夹的父文件夹中的Readme.md 文件,因此两个文件夹向上。

    因此,对于您的示例,如果 client_secret.json 始终与 .exe.dll 位于同一文件夹中,则解决方案相当简单。

    不要使用D:\client_secret.json,而是使用client_secret.json,它将始终首先查看当前目录。

    这是一个实际应用的示例

    byte[] nums = new byte[9];
    
    using FileStream fs = File.OpenRead("client_secret.json");
    
    fs.Read(nums, 0, nums.Length);
    
    fs.Close();
    
    fs.Dispose();
    
    Console.WriteLine(string.Join(", ", nums));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      • 2014-11-26
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 2012-12-26
      • 1970-01-01
      相关资源
      最近更新 更多