我想阅读我添加到项目根目录的文本文件的第一行.意思是,我的解决方案资源管理器在我的项目中的.cs文件旁边显示.txt文件.
所以,我试着这样做:
TextReader tr = new StreamReader(@"myfile.txt");
string myText = tr.ReadLine();
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为它指的是Bin文件夹,我的文件不在那里......我怎样才能使这个工作?:/
谢谢
dan*_*die 127
在Solution Explorer中,右键单击myfile.txt并选择"Properties"
从那里,设置Build Action
to content
和Copy to Output Directory
to之一Copy always
或Copy if newer
Man*_*kar 34
您可以使用以下命令获取网站项目的根目录:
String FilePath;
FilePath = Server.MapPath("/MyWebSite");
Run Code Online (Sandbox Code Playgroud)
或者您可以像这样获取基本目录:
AppDomain.CurrentDomain.BaseDirectory
Run Code Online (Sandbox Code Playgroud)
Eth*_*iac 29
将资源文件添加到项目中(右键单击项目 - >属性 - >资源).如果它表示"字符串",您可以切换为"文件".选择"添加资源"并选择您的文件.
您现在可以通过Properties.Resources
集合引用您的文件.
H.B*_*.B. 12
你可以嵌入它(构建动作设置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);
}
}
Run Code Online (Sandbox Code Playgroud)
Bru*_*lho 12
private string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
Run Code Online (Sandbox Code Playgroud)
上面的方法会带给你这样的东西:
"C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace\bin\Debug"
Run Code Online (Sandbox Code Playgroud)
从这里,您可以使用System.IO.Directory.GetParent向后导航:
_filePath = Directory.GetParent(_filePath).FullName;
Run Code Online (Sandbox Code Playgroud)
1次会到达\ bin,2次会到达\ myProjectNamespace,所以它会是这样的:
_filePath = Directory.GetParent(Directory.GetParent(_filePath).FullName).FullName;
Run Code Online (Sandbox Code Playgroud)
好吧,现在你有类似"C:\ Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace"的东西,所以只需附加你的fileName的最终路径,例如:
_filePath += @"\myfile.txt";
TextReader tr = new StreamReader(_filePath);
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你.
归档时间: |
|
查看次数: |
151919 次 |
最近记录: |