confused about split by backslash - c#

I am following a tutorial on internet and I have slightly changed the code for my purpose and now its not working. I have selected a path using OpenFileDialogand then tried to split selected file by backslash like below
C:\inetpub\logs\LogFiles\W3SVC1
and it always returns form1 instead file name, what am doing wrong?
string filename(string text)
{
string s = Text;
string[] arr = s.Split('\\');
string[] dot = arr[arr.Length - 1].Split('.');
return dot[0];
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
textBox1.Text = ofd.FileName;
label1.Text = filename(textBox1.Text);
}

and it always returns form1 instead file name, what am doing wrong?
You're not splitting the string text parameter at filename() method, but most likely the Text property of your Form (note that C# is case-sensitive, Text and text are completly 2 different things):
string filename(string text)
{
string s = Text;
string[] arr = s.Split('\\');
...
So change it to:
string s = text;
In addition, as suggested by others, you can use the Path.GetFileNameWithoutExtension() method which would provide you this desired logic easily:
var result = Path.GetFileNameWithoutExtension(fileName);

Your method parameter is called text but you split what you find in Text. C# is case-sensitive so Text must be a property on your Form...
By the way you can use LINQ to make your code a bit more readable. For instance you can replace arr[arr.Length - 1] by arr.Last(). Not what you asked for but a bonus tip anyway.
EDIT Yair's remark about System.IO.Path.GetFileNameWithoutExtension() is of course spot-on. Even better than doing the Split yourself and using LINQ to get the parts.

You do not need to parse it manually. You have a method to do that:
string file = Path.GetFileNameWithoutExtension(text);

C# is case-sensitive, text and Text refer to different values. In this case, you should replace:
string s = Text;
by
string s = text;
"text" being the argument passed to the filename function.

Related

How to create sub strings from raw bar code data with variable delimiter's/ delimiter order

I need to be able to pull sub strings out of a large string based on data identifiers. What is the proper method to pull specific strings of data?
I'll start with the fact I am a co-op student/ intern so go easy on me.
I am writing a program for a stand alone hand held computer scanner that will store the scanned data internally and transfer it to a computer when docked. (No RF or wireless on this particular site). I can scan a bar code and see the complete string of data no problem, its when I attempt to separate the data string into its variable parts (Part #, vender ID, Date, etc) that I cant get past. I can split the string based on each of the identifiers into a string array but im not sure how to call on the specific data sets based on the prefix data identifier so i can place the needed information into a data grid or export to excel properly.
Ultimately I would like to be able to define all of the different data identifiers( and there are a lot) and have my program go through each scan and pick out the needed information. Since this is a learning experience for me, Im not asking for someone to write it for me but point me in the right direction :)
If the identifiers are always the same between scans, I'd use string.Split
string[] stringArray = scannedString.Split(new string[]{"identifier1", "identifier2"}, StringSplitOptions.RemoveEmptyEntries);
Ive found that using regex has been the best solution.
The only problem I have now is that the my expressions can contain overlapping values. such as in the following code matching to:
[)>6P24274885Q641JUN631170227A0000027L20LA6-98721L54321 ZESKG11556D5-13-19 7:48 AM0366D190513MAY05-13-19011BKLT32147Q76GT2SDELNOTEPUSINV
The quantity is only 64 but my expression is adding the "1" from the 1JUN expression to its value, which is no good. So if anyone has any advice for preventing overlapping expressions? Otherwise Ill be getting learneded on regex methods.
//Define "Showmatch" and what to do when matches found
public void showMatch(string text, string expr, TextBox tb, Label lbl)
{
Regex regex = new Regex(expr);
Match match = regex.Match(text);
if (match.Success)
{
tb.Text = match.Value;
}
else
{
tb.Text = "No Data Found";
}
}
//Set Regular Expression Parameters
DateTime scan_Date = DateTime.Today;
string part_Param = "(P)[0-9-]+";
string serial_Param = "S[0-9-]+";
string duns_Param = "(1JUN)[0-9]+";
string quant_Param = "Q[0-9]+";
string unknown_Param = "20L-B[a-zA-Z0-9]";
public void button1_Click(object sender, EventArgs e)
{
//Pop up window to select data source document
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text Documents(*.txt)|*.txt", ValidateNames = true, Multiselect = true })
if (ofd.ShowDialog() == DialogResult.OK)
{
//Read Text Document From scanner
string[] raw_data = System.IO.File.ReadAllLines(ofd.FileName);
string mod_data = string.Join("", raw_data);
textBox1.Text = (mod_data);
tbScanDate.Text = scan_Date.ToString("dd.MM.yyyy");
showMatch(mod_data, part_Param, tbPartNumber, lblPartNumber);
showMatch(mod_data, serial_Param, tbSerialNumber, lblSerialNumber);
showMatch(mod_data, duns_Param, tbDunsNumber, lblDunsNumber);
showMatch(mod_data, quant_Param, tbQuantity, lblQuantity);
showMatch(mod_data, unknown_Param, tbOther, lblOther);
}

C# Reading a file into an array of strings and printing it into a Textbox

I have a problem with my code as a described it a little bit in the title.
So the thing I want to do is to read a number from a file and printing it into a TextBox but the only thing I can get written there is System.String[].
And here is my code:
private void ladenToolStripMenuItem_Click(object sender, EventArgs e)
{
// Kontostand aus Datei auslesen und in variable speichern anschließend in tb schreiben
string[] Kontostand = File.ReadAllLines(pathkonto);
string tbkontostand = Kontostand.ToString();
this.lbKontostand.Text = "Kontostand: " + tbkontostand + "€";
string[] Log = File.ReadAllLines(pathlog);
string LoginTextbox = Log.ToString();
this.tbLog.Text = LoginTextbox;
}
Maybe i should say that my Kontostand is an label which i want to look like that:
Kontostand: 500 €
And my file where i want to read that out looks like that:
500
Thanks for helping me out :)
Timm
You didn't specify, but it appears you're using Winforms. If so, you should use this:
string[] Log = File.ReadAllLines(pathlog);
this.tbLog.Lines = Log;
The default behavior of the ToString() method is to just return the name of the type of the object. The string[] type does not override the default behavior, so that's what you're getting in the text box.
However, the Winforms TextBox class has a Lines property of type string[]. So you just need to set that directly to the string[] you get from reading the file.
In your original code, you also want to include in a Label file lines from a different source, which you can easily do like this:
string[] Kontostand = File.ReadAllLines(pathkonto);
this.lbKontostand.Text = "Kontostand: "
+ string.Join("", Kontostand)
+ "€";
The Label control doesn't have a Lines property, so in this particular case, you do need to use something like string.Join().
Since Label controls also don't have a multi-line mode, I simply concatenate the contents of the file with the empty string as the separator. There'd be no point in using Environment.NewLine here. You could of course use any string you want instead of "". It's up to you.
Now, from your edited question, it appears you may not need any sort of multi-line support at all, because the data you describe is just a single line. If this is in fact the case, your code can be quite a lot simpler (and more efficient):
private void ladenToolStripMenuItem_Click(object sender, EventArgs e)
{
this.lbKontostand.Text = "Kontostand: "
+ File.ReadAllText(pathkonto)
+ "€";
this.tbLog.Text = File.ReadAllText(pathlog);
}
For that matter, if you simply want to copy the file contents into the respective controls, that's the way to do it anyway. Reading the contents in an array, only to copy the entire contents of that array into the control, is less efficient than just reading all of the file text and assigning it to the Text property directly. New-line characters will be read into the string returned by ReadAllText(), so whether the file contents are really multi-line or not, the above should work better than what you were originally trying to do.
The first thing you need is to be sure that your TextBox has the Multiline property set to true and that you have sized its height enough to see more than one line.
Next, you don't apply the ToString to an array of strings. This just produces the class name because arrays don't have an override of that method and thus they call the base Object.ToString().
Instead you can use AppendText to add first the fixed text, then string.Join to render the lines of your file followed by the final currency symbol.
private void ladenToolStripMenuItem_Click(object sender, EventArgs e)
{
string[] Kontostand = File.ReadAllLines(pathkonto);
this.lbKontostand.AppendText("Kontostand: " + Environment.NewLine)
this.lbKontostand.AppendText(string.Join(Environment.NewLine,tbkontostand);
this.lbKontostand.AppendText(" €");
}
Log.ToString(); just call ToString method of a string[] type variable.
you need to loop all strings in your array
foreach(string s in Log)
this.tbLog.Text += s+"\n";
string LoginTextbox = string.Join("\r\n", Log);
use string.Join to get a comma separated string of all the values in the array.

How can you trimend of textbox text from another textbox text

I have two textbox's textbox1 (read/write) & textbox2 (read only), textbox1 is where you enter text at which point you press a button to pass that text into textbox2 (textbox2 continually concatenates the text from textbox1). I have a second button that I want to press to remove the text from textbox2 that is still in textbox1. Can anyone suggest how to do this?
I was thinking;
string one = textbox1.text;
string two = textbox2.text;
string newTwo = two.trimend( value of string 'one' needs to be removed );
textbox2.text = newTwo;
textbox1;
world
textbox2;
hello world
I know this sounds odd but it's a bit of a work around for an algebra calculator.
If (textbox2.Text.EndsWith(textbox1.Text))
textbox2.Text = textbox2.Text.Substring(0, textbox2.Text.Length - textbox1.Text.Length);
you can do :
var start = two.IndexOf(one);
textbox2.text = two.Substring(start);
You can also use Replace method
string newTwo = two.Replace(one,"");
As far as i undestand your question boils down to "How to implement TrimEnd?". You can use code like this:
public static class StringExtensions
{
public static string TrimEnd(this string str,
string subject,
StringComparison stringComparison)
{
var lastIndexOfSubject = str.LastIndexOf(subject, stringComparison);
return (lastIndexOfSubject == -1
|| (str.Length - lastIndexOfSubject) > subject.Length)
? str
: str.Substring(0, lastIndexOfSubject);
}
}
Then is your code-behind:
textbox2.text = textbox2.text.TrimEnd(textbox1.text, StringComparison.CurrentCulture);
#jayvee is right. Replacing with string.Empty would do.
But there's one problem with that:
When replacing "Hello" in "Hello World" the leading whitespace would remain. newTwo would be " World". You may also would want to replace multiple whitespaces via Regex as posted here and then Trim() the new string.
Also this is case sensitive.

Display lins from text.file to array c#

I am trying to read lines from txt file into array and display it into a text box.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack != true)
{
blogPostTextBox.Text ="";
string blogFilePath = Server.MapPath("~") + "/Blogs.txt";
string[] blogMessageArray = File.ReadAllLines(blogFilePath);
// this for loop code does not work..I think..
for (int i = 0; i < blogMessageArray.Length; i++)
{
string[] fileLineArray = blogMessageArray[i].Split(' ');
blogPostTextBox.Text = blogMessageArray[i] + System.Environment.New Line.ToString();
}
}
}
My text file contains several line and I am trying to split each line to array and display all lines into a text box using a for loop or while loop.
UPDATE:
For ASP.Net
var items =File.ReadAllLines(blogFilePath).SelectMany(line => line.Split()).Where(x=>!string.IsNullOrEmpty(x));
blogPostTextBox.Text=string.Join(Environment.NewLine, items)
and as a side note, it is better to use Path.Combine when you build path from multiple strings
string blogFilePath = Path.Combine( Server.MapPath("~") , "Blogs.txt");
also if (IsPostBack != true) is valid but you can do as
if (!IsPostBack)
Winform
If the Multiline property of the text box control is set to true, you can use TextBoxBase.Lines Property
blogPostTextBox.Lines =File.ReadAllLines(blogFilePath);
if you need to split each line and set as textbox text then
blogPostTextBox.Lines = File.ReadAllLines(blogFilePath).SelectMany(line => line.Split()).ToArray();
You have to set TextMode="MultiLine" in your TextBox(default value is SingleLine), then you could build the text with Linq in this way:
var allLinesText = blogMessageArray
.SelectMany(line => line.Split().Select(word => word.Trim()))
.Where(word => !string.IsNullOrEmpty(word));
blogPostTextBox.Text = string.Join(Environment.NewLine, allLinesText);
You need to append each line to the textbox. What you are doing above is overwriting the contents of the textbox with each new line.
string[] blogMessageArray = File.ReadAllLines("");
blogPostTextBox.Text = "";
foreach (string message in blogMessageArray)
{
blogPostTextBox.Text += message + Environment.NewLine;
}
Although rather than read in all the lines, and then write out all the lines, why don't you just write out all the text to the textbox?
blogPostTextBox.Text = File.ReadAllText();
Though you could do this in a loop, you really don't need to (or want to)
Replace your loop with with built in dot net methods that actually do what your need.
See String.Join()
public static string Join(
string separator,
params string[] value
)
This will combine all of the elements of blogMessageArray with your specified separator
('\n' in your case, HTML does not need "\r\n")
Then just assign this to the property blogPostTextBox.Tex

how to find indexof substring in a text file

I have converted an asp.net c# project to framework 3.5 using VS 2008. Purpose of app is to parse a text file containing many rows of like information then inserting the data into a database.
I didn't write original app but developer used substring() to fetch individual fields because they always begin at the same position.
My question is:
What is best way to find the index of substring in text file without having to manually count the position? Does someone have preferred method they use to find position of characters in a text file?
I would say IndexOf() / IndexOfAny() together with Substring(). Alternatively, regular expressions. It the file has an XML-like structure, this.
If the files are delimited eg with commas you can use string.Split
If data is: string[] text = { "1, apple", "2, orange", "3, lemon" };
private void button1_Click(object sender, EventArgs e)
{
string[] lines = this.textBoxIn.Lines;
List<Fruit> fields = new List<Fruit>();
foreach(string s in lines)
{
char[] delim = {','};
string[] fruitData = s.Split(delim);
Fruit f = new Fruit();
int tmpid = 0;
Int32.TryParse(fruitData[0], out tmpid);
f.id = tmpid;
f.name = fruitData[1];
fields.Add(f);
}
this.textBoxOut.Clear();
string text=string.Empty;
foreach(Fruit item in fields)
{
text += item.ToString() + " \n";
}
this.textBoxOut.Text = text;
}
}
The text file I'm reading does not contain delimiters - sometimes there spaces between fields and sometimes they run together. In either case, every line is formatted the same. When I asked the question I was looking at the file in notepad.
Question was: how do you find the position in a file so that position (a number) could be specified as the startIndex of my substring function?
Answer: I've found that opening the text file in notepad++ will display the column # and line count of any position where the curser is in the file and makes this job easier.
You can use indexOf() and then use Length() as the second substring parameter
substr = str.substring(str.IndexOf("."), str.Length - str.IndexOf("."));

Categories