【发布时间】:2021-08-25 21:21:25
【问题描述】:
我正在尝试制作一个简单的 c# 程序,它使用 Visual Studio 在 dotnet core 5 中打开一个文件,但是,它发现它正在寻找与 .exe 存储位置相关的文件,而不是我的源文件。有什么办法可以改变这个吗?以便文件可以与我的源文件一起存储?
我尝试使用 Directory.GetCurrentDirectory(),但是,这会将我带到 .exe 文件,我需要使用相对路径而不是绝对路径打开它。
代码是从 Microsoft C# 文档 here 复制和粘贴的(在图像中,我在文件名前有一个“./”,我试过没有,这只是我试图让它工作的东西。
代码:
using System;
using System.IO;
namespace Test_File_Opening
{
class Program
{
static void Main(string[] args)
{
String line;
try
{
//Pass the file path and file name to the StreamReader constructor
StreamReader sr = new StreamReader("Sample.txt");
//Read the first line of text
line = sr.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
//write the lie to console window
Console.WriteLine(line);
//Read the next line
line = sr.ReadLine();
}
//close the file
sr.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
}
Exception: Could not find file 'C:\Users\callu\source\repos\Test_File_Opening\Test_File_Opening\bin\Debug\net5.0\Sample.txt'.
Executing finally block.
【问题讨论】:
-
使用所需文件的完整路径,而不是可执行文件的相对路径?
-
对不起,我没有提到这个,我需要它是一个相对路径,因为它需要能够在另一台机器上运行。
-
您还可以将构建时的文件自动复制到输出文件夹。看到这个有点不相关的问题,但图像适用:stackoverflow.com/a/26650101/5948452
-
如How to Ask所述,请将代码作为文本而不是文本图片提供。
-
当前目录总是指向exe所在的位置。您还提到您想在另一台机器上运行它。因此,请指定文件相对于 exe 位置的路径。您想要实现的是访问相对于您的源代码位置的文件,而不让您的 exe 知道您的源代码的位置。您可以将源文件夹位置提供给您的应用程序,然后让您的 exe 访问相对于它的位置。
标签: c# .net file .net-core .net-5