Comparing string with string from file [duplicate] - c#

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.

Related

Why Access path denied? [duplicate]

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");

File.ReadAllText prevents Form from closing on x button click

I have a weird problem. I want to write the visible textBox.Text to an "ini" file on FormClosing (right before the form shuts down), so I double clicked that event under the main form's Properties panel and filled the associated function as follows:
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
// store the whole content in a string
string settingsContent = File.ReadAllText(settingsPath + "CBSettings");
// replace a name with another name, which truly exists in the ini file
settingsContent.Replace(userName, userNameBox.Text);
// write and save the altered content back to the ini file
// settingsPath looks like this #"C:\pathToSettings\settingsFolder\"
File.WriteAllText(settingsPath + "CBSettings", settingsContent);
}
The form starts up without a problem, but it won't quit by clicking the x button. It only closes correctly when I comment the File.WriteAllText line out. If I just stop debugging, the files content doesn't change either.
EDIT :
The actual problem was the function which I used to find and return the userName from the ini file:
public static string GetTextAfterTextFromTextfile(string path, string file, string fileExtension, string textToLookFor)
{
string stringHolder;
StreamReader sr = File.OpenText(path + file + fileExtension);
while((stringHolder = sr.ReadLine()) != null)
{
if(stringHolder.Contains(textToLookFor))
{
return stringHolder.Replace(textToLookFor, "");
}
}
sr.Close();
return "Nothing found";
}
The content of the ini file:
User Name = SomeName
Bot Name = SomeName
I copied the above function from stackoverflow. I was sure that it worked because it captured 'SomeName' just as I wanted. Now I use another function (also from stackoverflow), that searches the ini file for 'User Name = ' and returns the text that comes right after it.
public static string GetTextAfterTextFromTextfile(string path, string textToSkip)
{
string str = File.ReadAllText(path);
string result = str.Substring(str.IndexOf(textToSkip) + textToSkip.Length);
return result;
}
The problem is, that it returns
SomeNameBot Name = SomeName
Any hint on how to limit string result to only one line? Many thanks in advance!
This is a normal mishap on the 64-bit version of Windows 7, caused by a nasty flaw in that operating system's Wow64 emulator. Not limited to Winforms apps, C++ and WPF apps are affected as well. For .NET apps, this only misbehaves if a debugger is attached. Repro code:
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
throw new Exception("You will not see this");
}
The debugger won't stop when the exception is thrown and you can't close the window anymore. I wrote a more extensive answer about this problem, including recommended workarounds, in this post.
Quick fix in your case: use Debug + Exceptions, tick the Thrown checkbox. The debugger now stops when the exception is thrown, allowing you to diagnose and fix your bug.

Modifying a Path (string) [duplicate]

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.

substring not working correctly [duplicate]

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

What is the easiest way to check a string whether it is a represents File name with full path in a correct Format? [duplicate]

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(...);
}
}

Categories

Resources