Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confused about split by backslash

Tags:

c#

split

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);
}
like image 299
user2751773 Avatar asked Jun 07 '26 23:06

user2751773


1 Answers

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);
like image 100
Yair Nevet Avatar answered Jun 10 '26 11:06

Yair Nevet