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");
This returns below:
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"));
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)
{
}
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.
You can get application path by
AppDomain.CurrentDomain.BaseDirectoryYour code must be like this
sStr = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataFile.txt");