我是C#的初学者,我有一个文件夹,我正在阅读文件。
我想读取位于解决方案文件的父文件夹中的文件。我该怎么做?
string path = "";
StreamReader sr = new StreamReader(path);
因此,如果我的文件XXX.sln
位于C:\X0\A\XXX\
,请阅读.txt
中的C:\X0\A\
个文件。
答案 0 :(得分:18)
试试这个:
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);
答案 1 :(得分: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;
}
}
用法:
// get directory
var directory = VisualStudioProvider.TryGetSolutionDirectoryInfo();
// if directory found
if (directory != null)
{
Console.WriteLine(directory.FullName);
}
在你的情况下:
// resolve file path
var filePath = Path.Combine(
VisualStudioProvider.TryGetSolutionDirectoryInfo()
.Parent.FullName,
"filename.ext");
// usage file
StreamReader reader = new StreamReader(filePath);
享受!
现在,警告..您的应用程序应该是解决方案无关的 - 除非这是一个我不介意的解决方案处理工具的个人项目。了解一下,您的应用程序一旦分发给用户将驻留在没有解决方案的文件夹中。现在,您可以使用“锚”文件。例如。像我一样搜索父文件夹并检查是否存在空文件app.anchor
或mySuperSpecificFileNameToRead.ext
; P如果您希望我编写方法,我可以 - 让我知道。
现在,您可能真的很享受! :d
答案 2 :(得分:6)
如果您的应用程序依赖于文件的位置(基于文件路径和解决方案路径之间的关系),那将是一种疏忽。虽然您的程序可能正在Solution/Project/Bin/$(ConfigurationName)/$(TargetFileName)
执行,但只有在Visual Studio的范围内执行时才有效。在Visual Studio之外,在其他情况下,情况不一定如此。
我看到两个选项:
将文件作为项目的一部分包含在内,并在其属性中将其复制到输出文件夹中。然后,您可以访问该文件:
string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Yourfile.txt");
请注意,在部署期间,您必须确保此文件也与可执行文件一起部署。
使用命令行参数指定启动时文件的绝对路径。这可以在Visual Studio中默认(请参阅项目属性 - >调试选项卡 - >命令行参数“。例如:
filePath="C:\myDevFolder\myFile.txt"
有许多关于解析命令行的方法和库。 Here's a Stack Overflow answer解析命令行参数。
答案 3 :(得分:2)
我认为这就是你想要的。不确定在发布时是否是个好主意:
string dir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName;
需要using System.IO;
答案 4 :(得分:1)
string path = Application.StartupPath;
答案 5 :(得分:1)
如果出于某种原因要在项目的解决方案路径中进行编译,则可以使用T4模板执行此操作。
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="EnvDTE" #>
<#@ import namespace="EnvDTE" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
<#@ parameter name="model" type="System.String" value=""#>
<#
IServiceProvider serviceProvider = (IServiceProvider)this.Host;
DTE dte = serviceProvider.GetService(typeof(DTE)) as DTE;
#>
using System;
using System.IO;
namespace SolutionInfo
{
public static class Paths
{
static string solutionPath = @"<#= Path.GetDirectoryName(dte.Solution.FullName) #>";
}
}
我认为Tah只能在Visual Studio中工作。