Parse string url to get filename

  • Thread starter Thread starter Netmonster
  • Start date Start date
The following is some code that searches an existing string for two other
strings (start marker and end marker), then gets only the required piece out
of the middle.


const string MODULE_LABEL = "/module";



// Get the command line parameters/arguments

ls_Argument = Environment.GetCommandLineArgs();

ls_Command_Line = String.Join(" ", ls_Argument);

ls_Command_Line = ls_Command_Line.Trim();

// Find the beginning of the /module parameter value

li_Position_Start = ls_Command_Line.IndexOf(MODULE_LABEL);

if (li_Position_Start == -1)

return -2011;

li_Position_Start += MODULE_LABEL.Length;



// Find end of the /module parameter value

li_Position_End = ls_Command_Line.IndexOf("/", li_Position_Start + 1);

if (li_Position_End == -1)

{

// use remainder of string

li_Position_End = ls_Command_Line.Length;

}

else

{

li_Position_End --;

}

// Get Module parameter value

ls_Parameter_Value = ls_Command_Line.Substring(li_Position_Start,
li_Position_End - li_Position_Start);

ls_Parameter_Value = ls_Parameter_Value.Trim();
 
Tom said:
Use a combination of Substring and LastIndexOf.

Something like:

string tmp = "http://test.com/downloads/test.exe";
int LastIndex = tmp.LastIndexOf("/");
tmp = tmp.Substring(LastIndex+1,(tmp.Length - LastIndex -1));
MessageBox.Show(tmp);

That works.

There are other ways to do it as well, such as using the String.Split()
function to split the string on the "/" char and then take the last item
in the array.

Lowell
 
Netmonster said:
Hello,

How do I parse a string that contains a URL and get the filename only?
i.e.

string tmp = "http://test.com/downloads/test.exe";
I just want the test.exe..
using System;
using System.IO;

class RemovePath
{
public RemovePath()
{
}
public static void Main(string[] args)
{
Console.WriteLine(System.IO.Path.GetFileName(args[0]));
}
}
 
Back
Top