C# store a string variable to a text file .txt - c#

How can i store the contents of a string variable to a text file ?
How can i search in a string variable for specific text for example find if the word book is in the string?

To save the file to text you can do:
System.IO.File.WriteAllText("C:\your_path\your_file", Your_contents);
To Search for something in the string:
var position = Your_string.IndexOf("Book");
If position equals -1 then what you are searching for isn't there.

In the off chance you are actually stumped on where to find this information, it's as simple as:
System.IO.File.WriteAllText(myPathToTheFile, myStringToWrite);
To find a string within another string, you would simply do this:
myString.Contains(someOtherString); // boolean
myString.IndexOf(someOtherString); // find the 0 based index of the target string

File.WriteAllText("MyFile.txt", myString); // Write all string to file
var wordBookIndex = myString.IndexOf("book"); // If the string is found, index != -1

System.IO namespace has various methods and classes for file (and other) IO, this one may serve your purpose easily:
http://msdn.microsoft.com/en-us/library/system.io.file.writealltext.aspx
As for searching inside a single string, use String.IndexOf:
http://msdn.microsoft.com/en-us/library/system.string.indexof.aspx

answer to 1 question
make use of System.IO namespace in that there are not class availabe to wirte the text in file
answer to 2 question
you can use Regular expression or make use of IndexOf function to serach specific word in string

Related

Extract second section of string

I will have always an string like this:
"/FirstWord/ImportantWord/ThirdWord"
How can I extract the ImportantWord? Words can contain at most one space and they are separated by forward slashlike I put above, for example:
"/Folder/Second Folder/Content"
"/Main folder/Important/Other Content"
I always want to get the second word(Second Folder and Important considering above examples)
how about this:
string ImportantWord = path.Split('/')[2]; // Index 2 will give the required word
I hope you need not to use the String.Split option either with specific characters or with some regular expressions. Since the inputs are well qualified paths to a directory you can use Directory.GetParent method of the System.IO.Directory class, which will give you the parent Directory as DirectoryInfo. From that you can take the Name of Directory which will be the required text.
You can use like this :
string pathFirst = "/Folder/Second Folder/Content";
string pathSecond = "/Main folder/Important/Other Content";
string reqWord1 = Directory.GetParent(pathFirst ).Name; // will give you Second Folder
string reqWord2 = Directory.GetParent(pathSecond).Name; // will give you Important
Additional note: The method Directory.GetParent can be nested if you need to get a name in another level.
Also you may try this:
var stringValue = "/FirstWord/ImportantWord/ThirdWord";
var item = stringValue.Split('/').Skip(2).First(); //item: ImportantWord
There are several ways to solve this. The simplest one is using String.split
Char delimiter = '/';
String[] substrings = value.Split(delimiter);
String secondWord = substrings[1];
(you may want to do some input check to make sure the input is in the right format or else you will get some exception)
Other way is using regex when the pattern is simple /
If you are sure this is a path you can use other answer mention here

C# - using string contains with string array

I have a question regarding C#, strings and arrays.
I've searched for similar questions at stack overflow, but could not find any answers.
My problem:
I have a string array, which contains words / wordparts to check file names. If all of these strings in the array matches, the word is "good".
String[] StringArray = new String[] { "wordpart1", "wordpart2", ".txt" };
Now I want to check if all these strings are a part of a filename. If this checkresult is true, I want to do something with this file.
How can I do that?
I already tried different approaches, but all doesn't work.
i.e.
e.Name.Contains(StringArray)
etc.
I want to avoid to use a loop (for, foreach) to check all wordparts. Is this possible?
Thanks in advance for any help.
Now I want to check if all these strings are a part of a filename. If this checkresult is true, I want to do something with this file. How can I do that?
Thanks to LINQ and method groups conversions, it can be easily done like this:
bool check = StringArray.All(yourFileName.Contains);
Similar question: Using C# to check if string contains a string in string array
This uses LINQ:
if(stringArray.Any(stringToCheck.Contains))
This checks if stringToCheck contains any one of substrings from
stringArray. If you want to ensure that it contains all the
substrings, change Any to All:
if(stringArray.All(s => stringToCheck.Contains(s)))

How to get filename from a file "template.docx.amp" in c#?

I have got a strange template whose extension is ".docx.amp" . Now i want to get fileName. i.e "template". Path.GetFileNameWithoutExtension() fails as it returns template.docx. Is there any other built in mechanism or i will have to go the ugle string comparison/split way. Please suggest and give some workaround
Nope, you will have to use some kind of string split, eg:
var nameWithoutExtension = filename.Split('.')[0];

String manipulation in C#: split on `/`

I need to extract headstone data from an inscription file (structured text file). From this file I am supposed to extract the name of a deceased person, date of birth (or age) and also personal messages. The application should be able to analyse a raw text file and then extract information and display it in tabular form.
The raw text files looks like this:
In loving memory of/JOHN SMITH/who died on 13.02.07/at age 40/we will
miss you/In loving memory of/JANE AUSTIN/who died on 10.06.98/born on
19.12.80/hope you are well in heaven.
Basically / is a delimiter and the name of a deceased person is always in capital letters. I have tried to use String.Split() and substring methods but I can't get it to work for me; I can only get raw data without the delimiter (Environment.Newline) but I don't know how to extract specific information.
You'll need something like:
Open your data file (System.IO)
For each line, do (tip: pick a stream where you can read line by line)
Split them by "/" getting a string[]
Arrays in C# starts at 0; so splitted[1] will be that name, ans so on
Store that information in a managed collection (maybe to use generics?)
Display that collection in a tabular view
Check out How to: Use Regular Expressions to Extract Data Fields. I know the example is in C++, but the Regex and Match classes should help you get started
Here is another good example of parsing out individual sentences.
I would have thought something like this would do the trick
private static void GetHeadStoneData()
{
using(StreamReader read = new StreamReader("YourFile.txt"))
{
const char Delimter = '/';
string data;
while((data = read.ReadLine()) != null)
{
string[] headStoneInformation = data.Split(Delimter);
//Do your stuff here, e.g. Console.WriteLine("{0}", headStoneInformation[0]);
}
}
}

C# Reading file and pulling out specific lines

Thanks in advance. What i currently have is a filedialog box selecting a text file. The text file contents will look like example.txt, and it needs to look like output.txt. NOTE: the string CoreDBConnectString= is 1 line all the way to ;Database=Source_DB.
example.txt
[Information]
Date=
CreatedBy=
Unique=eqwe-asd-123-as12-3
CoreDataSource=
CoreDBConnectString=Provider=SQLOLEDB.1;Server=Server;Integrated Security=SSPI;Database=Source_DB
NoteDataSource=SQLServer
NoteDBConnectString=Provider=Provider=SQLOLEDB.1;Server=Server;Integrated Security=SSPI;Database=Source_DB
CoreDBCaseID=99
NoteDBCaseID=99
Output.txt
Table=99 (Comes from CoreDBCaseID)
Server=Server (comes from the string CoreDBConnectString=)
Security=SSPI (comes from the string CoreDBConnectString=)
Database=Source_DB (comes from the string CoreDBConnectString=)
You can do something like this:
// Load the file contents
string contents = File.ReadAllText("example.txt");
// Obtain the data using regular expressions
string id = string id = Regex.Match(
contents,
#"CoreDBCaseID=(?<id>\d+)").Groups["id"].Value;
string server = string.Empty; // Add regex here
string security = string.Empty; // Add regex here
string database = string.Empty; // Add regex here
// Save the data in the new format
string[] data = new string[] {
String.Format("Table={0}", id),
String.Format("Server={0}", server),
String.Format("Security={0}", security),
String.Format("Database={0}", database)
};
File.WriteAllLines("output.txt", data);
And a quick way to learn those regular expressions:
Regular Expression Cheat Sheet
Regular-Expressions.info
You can use a positive lookahead to stop matching at the (;) character. Something like this:
#"Security=(?[\D]+)(?=;)"
That is an INI file, which is very old school. Nowadays, we programming folks use XML instead. Consequently, there is no built-in support for INI files in C#.
You can P/Invoke GetPrivateProfileString to read the data.
You can use WritePrivateProfileString to write the new data out if you don't mind the information section header like so :
[Information]
Table=99
Server=Server
Security=SSPI
Database=Source_DB
This CodeProject article on INI-file handling with C# may help.
I would use a combination of StreamReader.ReadLine and RegEx to read each line and extract the appropriate information.
Open the file and read it in one line at a time. You can use Regular Expressions (cheat sheet) to match and parse only the text you want to find.
INI files are old skool. Thus, someone has already written a class for it: http://www.codeproject.com/KB/cs/readwritexmlini.aspx. The class linked reads XML, INI, Registry, and Config Files.

Categories