Use*_*501 11 c# io file path streamreader
我是C#的初学者,我有一个文件夹,我正在从中读取文件.
我想读取位于解决方案文件的父文件夹中的文件.我该怎么做呢?
string path = "";
StreamReader sr = new StreamReader(path);
Run Code Online (Sandbox Code Playgroud)
所以如果我的文件XXX.sln在C:\X0\A\XXX\那里,那么读取.txt文件C:\X0\A\.
Thi*_*a H 19
试试这个:
string startupPath = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName,"abc.txt");
// Read the file as one string.
string text = System.IO.File.ReadAllText(startupPath);
Run Code Online (Sandbox Code Playgroud)
Dem*_*tos 10
您可能会喜欢这种更通用的解决方案,它依赖于*.sln通过扫描当前或选定的父目录来查找解决方案文件,同时覆盖未找到解决方案目录的情况!
public static class VisualStudioProvider
{
public static DirectoryInfo TryGetSolutionDirectoryInfo(string currentPath = null)
{
var directory = new DirectoryInfo(
currentPath ?? Directory.GetCurrentDirectory());
while (directory != null && !directory.GetFiles("*.sln").Any())
{
directory = directory.Parent;
}
return directory;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
// get directory
var directory = VisualStudioProvider.TryGetSolutionDirectoryInfo();
// if directory found
if (directory != null)
{
Console.WriteLine(directory.FullName);
}
Run Code Online (Sandbox Code Playgroud)
在你的情况下:
// resolve file path
var filePath = Path.Combine(
VisualStudioProvider.TryGetSolutionDirectoryInfo()
.Parent.FullName,
"filename.ext");
// usage file
StreamReader reader = new StreamReader(filePath);
Run Code Online (Sandbox Code Playgroud)
请享用!
现在,警告..您的应用程序应该是解决方案无关的 - 除非这是一个解决方案处理工具的个人项目,我不介意.了解一下,一旦分发给用户,您的应用程序将驻留在没有解决方案的文件夹中.现在,您可以使用"锚"文件.例如,像我一样搜索父文件夹并检查是否存在空文件; app.anchor或者mySuperSpecificFileNameToRead.extP如果您希望我编写方法,我可以 - 让我知道.
现在,你可能真的很享受!:d
如果您的应用程序依赖于文件的位置(基于文件路径和解决方案路径之间的关系),那将是疏忽.虽然您的程序可能正在执行Solution/Project/Bin/$(ConfigurationName)/$(TargetFileName),但只有在Visual Studio的范围内执行时才有效.在Visual Studio之外,在其他情况下,情况不一定如此.
我看到两个选择:
将文件作为项目的一部分包含在其属性中,将其复制到输出文件夹中.然后,您可以访问该文件:
string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Yourfile.txt");
Run Code Online (Sandbox Code Playgroud)
请注意,在部署期间,您必须确保此文件也与可执行文件一起部署.
使用命令行参数指定启动时文件的绝对路径.这可以在Visual Studio中默认(请参阅项目属性 - >调试选项卡 - >命令行参数".例如:
filePath="C:\myDevFolder\myFile.txt"
Run Code Online (Sandbox Code Playgroud)
解析命令行有很多方法和库.这是解析命令行参数的Stack Overflow答案.