我想读取我添加到项目根目录中的文本文件的第一行。也就是说,我的解决方案资源管理器显示了我的项目中的.cs文件以及.txt文件。
因此,我尝试做:
TextReader tr = new StreamReader(@"myfile.txt");
string myText = tr.ReadLine();
但是这并不起作用,因为它正在引用Bin文件夹,而我的文件不在其中... 我该如何使其起作用? :/
谢谢
我想读取我添加到项目根目录中的文本文件的第一行。也就是说,我的解决方案资源管理器显示了我的项目中的.cs文件以及.txt文件。
因此,我尝试做:
TextReader tr = new StreamReader(@"myfile.txt");
string myText = tr.ReadLine();
但是这并不起作用,因为它正在引用Bin文件夹,而我的文件不在其中... 我该如何使其起作用? :/
谢谢
从“解决方案资源管理器”中,右键点击 myfile.txt 文件并选择“属性”
接着,在那里把 Build Action
设置为 content
,
并将Copy to Output Directory
设置为 始终复制(Copy always)
或者 仅在较新时复制(Copy if newer)
您可以使用以下代码获取网站项目的根目录:
String FilePath;
FilePath = Server.MapPath("/MyWebSite");
或者你可以这样获取基本目录:
AppDomain.CurrentDomain.BaseDirectory
将资源文件添加到项目中(右键单击项目->属性->资源)。在“字符串”处,您可以切换到“文件”。选择“添加资源”并选择您的文件。
现在,您可以通过Properties.Resources
集合引用您的文件。
private string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
上述方法将会给你带来像这样的东西:
"C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace\bin\Debug"
您可以使用 System.IO.Directory.GetParent 后退导航:
_filePath = Directory.GetParent(_filePath).FullName;
一次将带您到 \bin,两次将带您到 \myProjectNamespace,因此会是这样:
_filePath = Directory.GetParent(Directory.GetParent(_filePath).FullName).FullName;
现在你有了类似"C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace"的路径,所以只需将最终路径附加到你的文件名上即可,例如:
_filePath += @"\myfile.txt";
TextReader tr = new StreamReader(_filePath);
希望这有所帮助。
您也可以将它嵌入(构建操作设置为 Resource
),这是从中检索它的方法:
private static UnmanagedMemoryStream GetResourceStream(string resName)
{
var assembly = Assembly.GetExecutingAssembly();
var strResources = assembly.GetName().Name + ".g.resources";
var rStream = assembly.GetManifestResourceStream(strResources);
var resourceReader = new ResourceReader(rStream);
var items = resourceReader.OfType<DictionaryEntry>();
var stream = items.First(x => (x.Key as string) == resName.ToLower()).Value;
return (UnmanagedMemoryStream)stream;
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
string resName = "Test.txt";
var file = GetResourceStream(resName);
using (var reader = new StreamReader(file))
{
var line = reader.ReadLine();
MessageBox.Show(line);
}
}
在这种情况下,您必须使用绝对路径。但是,如果您设置了CopyToOutputDirectory = CopyAlways
,它将像您正在执行的那样工作。
在这段代码中,您可以访问root
项目目录:
string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
那么:
StreamReader r = new StreamReader(_filePath + "/cities2.json"))