This question already has answers here:
Modify path string to improve robustness
(2 answers)
Closed 8 years ago.
I want my program to be able to get the the relevant directory to grab information from a text file to improve robustness.
So this is the method I made:
public void GetPath()
{
var directory = Directory.GetCurrentDirectory();
hs.Path = directory.Replace(#"\\EventDriven\\bin\\Debug", hs.ReplacePath);
}
This is the relevant property and strings (I'm aware I can declare them both in one go):
(Originally the path was hardcoded as you can see)
private string path = #"C:\Users\zain\Desktop\program_storage\AccountDatabase.txt";
private const string replacePath = #"Data\AccountDatabase.txt";
public string Path
{
get { return path; }
set { this.path = value; }
}
public string ReplacePath { get { return replacePath; } }
This is the path I get before I try to replace any of the path:
"E:\\Work\\To do\\QA\\program_storage\\program_storage\\bin\\Debug"
This is the directory of where the AccountDatbabase.txt file will be in:
E:\Work\To do\QA\program_storage\Data
So the final directory it should attempt to access is:
E:\Work\To do\QA\program_storage\Data\AccountDatabase.txt
What seems to get stored in (hs.)Path is
"E:\\Work\\To do\\QA\\program_storage\\program_storage\\bin\\Debug"
despite usng the replace?
I want the program to work on multiple windows machines. I think I might have a problem with the get set property I made (I'm aware I can remove this. from it) but that should just throw an error? I'm probably not using replace correctly?
Thanks for all and any help provided! (please don't remove this thank you message again)
Add an app.config file to your application.
Add a appSettings section to that file and add a key that contains your file path
When you need the path, call ConfigurationManager.AppSettings["thekeynameyouused"] to get the path.
Related
This question already has answers here:
Access to the path is denied when saving image
(26 answers)
Closed 5 years ago.
I'm trying to read a text file with File.ReadAllText and FileStream, but for some reason I get the System.UnauthorizedAccessException every time.
class consultas
{
public consultas()
{
}
private string Inativos = #"C:\Users\Mathias Cruz\Desktop\helloWorld\helloWorld\Consultas";
public string getInativos()
{
try
{
// string path = Directory.GetCurrentDirectory();
this.Inativos = File.ReadAllText(this.Inativos);
}
catch(Exception e)
{
throw e;
}
return this.Inativos;
}
}
Why? I have permissions in that folder, so why do I get this exception?
Based on your code, you are either trying to read a Folder since you didn't specify a extension on your File Path here:
private string Inativos = #"C:\Users\Mathias Cruz\Desktop\helloWorld\helloWorld\Consultas";
It will definitely throw a UnauthorizedAccessException error. So make sure you have the exact file path together with its extension.
Because the path is a directory.
Please check your file address.
This method needs a file address.
Here is a sample code:
File.ReadAllText("C:\\yourfile.txt");
This question already has answers here:
How to read an entire file to a string using C#?
(17 answers)
Closed 8 years ago.
I have declared a string that holds all the current settings of a device string settings = "". I want to compare that to another string which holds the correct settings for that device which is saved in a text file. If both strings are equal then I know no changes need to be made to the settings as they are correct.
The .PFL file is in a dropdown menu of other settings. So I have the string of the settings file and want to compare that to the string on the .PFL file.
I have a snippet of the code I have done so far, think I'm on the right track. If i declared another string it would be simple to compare but how would I compare from a string on a text file.
private void button1_Click(object sender, EventArgs e)
{
Cancel = false;
string Settings = "S0=80,S1=01,S2=7F2037,S3=44,S4=081E,S5=8832,S6=8846,S7=00,S8=00,SS15=84.51.244.10,S16=9000,S17=0049351928,S18=500,S19=0000,S20=00,S21=,S22=,S23=13,S24=00,S25=00,S26=00,S27=19";
UpdateConsole(Settings + "\r\n");
string c = Settings.Trim();
if(c==d)
{
UpdateConsole("Pass Settings are equal");
}
}
You can use File.ReadAllText(<pathoffile>) to read the file into a string, and compare that to your other string.
This question already has answers here:
How to split string using Substring
(7 answers)
Closed 8 years ago.
im trying to make c# read text from each line in a txt file then set a variable based on the line this is the code im trying to use
string line;
FileInfo file = new FileInfo("update.txt");
StreamReader stRead = file.OpenText();
while ((line = stRead.ReadLine()) != null)
{
if (line.StartsWith("version=") == true)
{
Version.TryParse(line.Substring(8), out version);
}
if (line.StartsWith("md5=") == true)
{
md5 = line.Substring(4);
}
if (line.StartsWith("url=") == true)
{
url = line.Substring(4);
}
if (line.StartsWith("changelog=") == true)
{
changelog = line.Substring(10);
}
}
stRead.Close();
i put breakpoints in to see what was happening and its reading the txt file but not setting the variables for some reason i declared these variables above the code
private Version version;
private string md5;
private string url;
private string changelog;
only the version variable gets set please help thanks
oh and this is the test txt im using
version=1.1.0.0
md5=564C8AACFBDAA1F5A0AA44A85C53BF55
url=fbnfhbcfn
changelog=bug fixes
The code is fine the way it is. Some things to keep in mind:
The text file update.txt needs to be in the same directory as the executable. So, if a console application or a windows application it should be in bin/Debug, when you start debugging for instance. If you have included it in your project, ensure that the build action is set to "Content", and "Copy to Output Directory" is set to "Always". (This is found under the properties of the file in the solution).
The file update.txt needs to be readable by the executable/runtime
I have an application written in C#, and I am seeking to write some information to the hidden ProgramData in order to access the same connection string from both the application's front end and back end.
I am accessing the directory using path variables as follows:
private bool ProgramDataWriteFile(string contentToWrite)
{
try
{
string strProgramDataPath = "%PROGRAMDATA%";
string directoryPath = Environment.ExpandEnvironmentVariables(strProgramDataPath) + "\\MyApp\\";
string path = Environment.ExpandEnvironmentVariables(strProgramDataPath)+"\\MyApp\\ConnectionInfo.txt";
if (Directory.Exists(directoryPath))
{
System.IO.StreamWriter file = new System.IO.StreamWriter(path);
file.Write(contentToWrite);
file.Close();
}
else
{
Directory.CreateDirectory(directoryPath);
System.IO.StreamWriter file = new System.IO.StreamWriter(path);
file.Write(contentToWrite);
file.Close();
}
return true;
}
catch (Exception e)
{
}
return false;
}
This seems to work correctly. However, my question is, when I used this path variable: %AllUsersProfile%(%PROGRAMDATA%)
instead, it expanded into an illegal(and redundant) file path : C:\ProgramData(C:\ProgramData)\
However, I thought that the latter path variable was the correct full name. Was I just using it incorrectly? I need to ensure that this connection info will be accessible to all users, will just using %PROGRAMDATA% allow that? I am using Windows 7 in case that is relevant.
From here:
FOLDERID_ProgramData / System.Environment.SpecialFolder.CommonApplicationData
The user would never want to browse here in Explorer, and settings changed here should affect every user on the machine. The default location is %systemdrive%\ProgramData, which is a hidden folder, on an installation of Windows Vista. You'll want to create your directory and set the ACLs you need at install time.
So, just use %PROGRAMDATA%, or better still:
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Figuring out whether string is valid file path?
In C# check that filename is *possibly* valid (not that it exists)
I have a method that expects a string which represents a file name with its full path.
I want to validate (Guard) this string in terms of its format to see whether it CAN really represent a file name (not the correctness of the path whether it exists or not)?
For example it should not be accepted if it is something like : "123C:\foo\"
What is the easiest way to do this check in C# ?
public void LoadFile(string fileName)
{
var valid = Check if 'fileName' is in valid format.
if(!valid)
throw new ArgumentException(....
}
From the documentation:
In members that accept a path as an input string, that path must be well-formed or an exception is raised.
So you can do something like this:
public void LoadFile(string fileName)
{
try
{
var path = Path.GetFullPath(fileName);
}
catch (NotSupportedException e)
{
throw new ArgumentException(...);
}
}