substring not working correctly [duplicate] - c#

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

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

Comparing string with string from file [duplicate]

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.

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.

Check if path is in Program Files [duplicate]

This question already has answers here:
See if file path is inside a directory
(2 answers)
Closed 9 years ago.
How can I check in C# if the specific path is to directory in "Program Files" ?
C:\Program Files\someDir... -> is in Program Files
D:\Apps\someDir... -> isn't in Program Files
Thanks!
You can check a path in ProgramFiles(x86) by using the code below:
string path = "yourpath";
var programfileX86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
if (path.IndexOf(programfileX86, StringComparison.OrdinalIgnoreCase) >= 0)
{
//Found path
}
There're some interseting and subtle issues with the problem:
You should compare paths case insenstive, e.g. "C:\PRogRAM FILES (x86)\Sample" is OK
Separators could be either / or \ so "C:/PRogRAM FILES (x86)/Sample" is OK as well
You should break on separatos only, e.g. "C:\Program Files (x86)MyData\Sample" is not OK
The Code:
public static Boolean PathIncludes(String path, String pathToInclude) {
if (String.IsNullOrEmpty(pathToInclude))
return false;
else if (String.IsNullOrEmpty(path))
return false;
String[] parts = Path.GetFullPath(path).Split(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar, Path.VolumeSeparatorChar);
String[] partsToInclude = Path.GetFullPath(pathToInclude).Split(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar, Path.VolumeSeparatorChar);
if (parts.Length < partsToInclude.Length)
return false;
for (int i = 0; i < partsToInclude.Length; ++i)
if (!String.Equals(parts[i], partsToInclude[i], StringComparison.OrdinalIgnoreCase))
return false;
return true;
}
public static Boolean InProgramFiles(String path) {
return PathIncludes(path, Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)));
}
// Tests:
// Supposing that ProgramFilesX86 is "C:\Program Files (x86)"
InProgramFiles(#"C:\PRogRAM FILES (x86)\Sample"); // <- true
InProgramFiles(#"C:/PRogRAM FILES (x86)/Sample"); // <- true
InProgramFiles(#"D:/PRogRAM FILES (x86)/Sample"); // <- false
InProgramFiles(#"C:/PRogRAM FILES (x86)A/Sample"); // <- false
First you need to get the program files path. You can do that with System.Environment:
var programFilesPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles);
If you want the 32 bit program files path you would just change the special folder you are looking for (System.Environment.SpecialFolder.ProgramFilesX86). Then I would do a contains:
var isInProgramFiles = myPath.ToLower().Contains(programFilesPath.ToLower());
That should get you 90% of the way there at least! Best of luck!
EDIT / Sanitize Note
As a side note - there are situations where you can have a valid input and this still wouldn't match. For example - using "/" instead of "\". If you want to make sure you handle these boundary cases correctly, you can create a "DirectoryInfo" object from your input string, validate that it is actually a folder and also standardize the formatting for it. That code looks something like:
if (!System.IO.Directory.Exists(inputPath)) return false;
var checkPath = (new System.IO.DirectoryInfo(inputPath)).FullName;
In this example "inputPath" is the same as "myPath" was above. That should do a moderately good job of sanitizing the input. Best of luck!
If you have a path variable:
string path = "/* whatever path */";
You can check if it is in a folder subfolder this way:
path.IndexOf('\\' + subfolder + '\\') != -1
Note that in more complex cases .. may revert you out of a subdirectory, meaning that you are not in folder f2 if you have something like this:
"\\base_on_drive\\subfolder\\f1\\f2\\..\\a_file.txt"
The .. will bump you back into it's parent folder f1.
if (path.Contains(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)) || (path.Contains(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)))
{
}
Assuming your program might be running inside of ProgramFiles, you will probably want to get the fullpath of any path you're checking (in case you get a relative path). In addition, C# has a handy SpecialFolder enumeration that you can use to get the ProgramFiles directory.
The following code will take in a path, convert it to a fullpath, and check if the ProgramFiles directory can be found inside of it. You may want to add some error handling (such as checking for null paths).
static string programfileX86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
public bool IsInsideProgramFiles(string path)
{
// Get the fullpath in case 'path' is a relative path
string fullPath = System.IO.Path.GetFullPath(path);
return (fullPath.IndexOf(programfileX86, StringComparison.OrdinalIgnoreCase) >= 0);
}
Note: Depending on the systems your code is running in, you may want to check for both SpecialFolder.ProgramFiles and SpecialFolder.ProgramFilesx86.
Credit goes to Toan Nguyen's for the code to get the ProgramFiles directory:

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