Click here to Skip to main content
15,908,455 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can i store text from a text file in a string. i only want to store text between two self specified symbols..e.g
if txt file contains :

jhon upload_file # C:\Myfolder #

i only want to store text between the two # symbols i.e the string only stores
c:\Myfolder

thanks
Posted

the following should work:

C#
string strng = "dsksf#dfkfdsafl#dsfksa";
var s = strng.Substring(strng.IndexOf("#") + 1, strng.LastIndexOf("#") - strng.IndexOf("#") - 1);
var sw = new StreamWriter(@"C:\Users\clifford\Documents\text.txt");
sw.Write(s);
sw.Close();


Here I am assuming you want to store the string, not save the string, if you want to open a text file to get the string you can use the following:

C#
var sr = new StreamReader(@"C:\Users\clifford\Documents\text.txt");
var x = sr.ReadToEnd();
sr.Close();


Be careful with your words, store would be to disk.
 
Share this answer
 
v2
Comments
Ghost_x 1-Apr-12 4:19am    
Thanks a lot.
yeah i only have to use the string at runtime.
i dont have to save it on disk.

p.s im a student and new to c#
Use the String.IndexOf function to get location of the # character.
Use the String.LastIndexOf function to get location of the last # character.
Then, just use String.SubString method[^] to get the characters in the middle set.
 
Share this answer
 
Hi,

There's an alternative solution to Clifford's string slicing answer. You could use Regex to do this.
Regex is very powerful and is a very well suited at string manipulation.

In your case you could do it like this:
C#
string strng = "dsksf#dfkfdsafl#dsfksa";
Match match = Regex.Match(strng, "#.*#");
string result = match.Value.Substring(1, match.Value.Length - 2);


There are plenty on resources on Regex available:
http://msdn.microsoft.com/en-us/library/c75he57e.aspx[^]
http://www.regular-expressions.info/[^]

There are also a few online regex testers:
http://www.pagecolumn.com/tool/regtest.htm[^]

Valery.
 
Share this answer
 
v2
Comments
Ghost_x 1-Apr-12 10:23am    
Looks great! but i was having issue with this solution.
there was sort of conflict between variables after adding system.text.regularexpressions
Clifford Nelson 1-Apr-12 16:36pm    
This is a high cost search. If you do not need regular expressions, don't use them.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900