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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With