如果在c#中文件位置未知,如何从文本文件中读取数据? [英] How to read data from a text file if the file location is not known in c#?

查看:34
本文介绍了如果在c#中文件位置未知,如何从文本文件中读取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前在StackOverFlow中已经问过这个问题,并且在该帖子中也标记了答案.但是可悲的是提供的解决方案从未知位置读取文件?不能解决我的问题.
我正在建立一个网站,需要从一个文本文件中读取数据.文件在我的PC中的实际位置是: C:\ Developments \ TestProject \ PettyCashSolution \ PettyCashWeb \ DataFile.txt 和我已经尝试过从上面的链接下面的解决方案没有运气.

This question have been asked earlier in StackOverFlow and answers are also marked in that post. But sadly the solution provided in Read a file from an unknown location? does not solve my problem.
I am building a website and need to read data from a text file. The actual location of the file in my pc is: C:\Developments\TestProject\PettyCashSolution\PettyCashWeb\DataFile.txt and I have tried below solutions from above link with no luck.

string sString = string.Empty;
string sStr = "";
StreamReader oStreamReader;
try
{ 

Try1

sStr = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "DataFile.txt");

以下返回:
C:\ WINDOWS \ Microsoft.NET \ Framework \ v2.0.50727 \ Temporary ASP.NET Files \ pettycashweb \ af7f0870 \ c5ac294a \ DataFile.txt

Try2

sStr = Path.Combine(Application.StartupPath, "DataFile.txt");

以下返回:
编译错误:名称应用程序"在当前上下文中不存在

This returns below:
Compile Error: The name "Application" does not exist in the current context

Try3

oStreamReader = new StreamReader(File.OpenRead(Directory.GetCurrentDirectory().ToString() + "\\DataFile.txt"));

以下返回:
例外:找不到文件'C:\ Program Files \ Microsoft Visual Studio 8 \ Common7 \ IDE \ DataFile.txt'

This returns below:
Exception: Could not find file 'C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\DataFile.txt'

oStreamReader = new StreamReader(sStr);
sString = oStreamReader.ReadLine();

}
catch (Exception ex)
{
}

也请告知我应该怎么做,以便在服务器(iis)中发布网络后,从文本文件读取的数据将正常工作.谢谢.

Please also advice what should I do so that after publishing the web in server (iis) the read data from text file will work properly. Thanks.

推荐答案

您可以通过 AppDomain.CurrentDomain.BaseDirectory

您的代码必须是这样

sStr = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"DataFile.txt");

这篇关于如果在c#中文件位置未知,如何从文本文件中读取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆