How to get FileName from url - c#

I have url like http://xxx.xxx.xxx/mls/pmmls/12/-8/53/6/12-8536_2.jpg/t1349940727/100x100/
and need to get only filename from url like "12-8536_2.jpg"
url format is dynamic. Filename with extension must be in url. but it filename with extension may not be in last position of url
I have tried Path.GetFileName() but it give "".
is anyone know how extract filename for this type of url?

12-8536_2.jpg does not seem to be a file in that URL. In any case, if the "filename" in the URL will always be in .jpg, you can output the URL to a string (or AS a string) and Regex for it:
string filename = Regex.Match(URL,#"\/([A-Za-z0-9\-._~:?#\[\]#!$%&'()*+,;=]*).jpg").Groups[1].Value
EDIT: I'm thinking this is for a site with different preview sizes for a specific file. You can also specify the different possible extensions as follows (for example):
string filename = Regex.Match(URL,#"\/([A-Za-z0-9\-._~:?#\[\]#!$%&'()*+,;=]*)(.jpg|.JPG|.jpeg|.JPEG)").Groups[1].Value

There is no guarantee that any part of a URL maps to a file, so it does not make sense to try to get the FileName in a URL.

If you know the filename will always be followed by two further segments (in your example, t1349940727 and 100x100), you could do
var input =
"http://xxx.xxx.xxx/mls/pmmls/12/-8/53/6/12-8536_2.jpg/t1349940727/100x100/";
var uri = new Uri(input);
var fileName = uri.Segments[uri.Segments.Length - 3];
If you don't know that, then as others have said, there's no easy way to tell which part is the filename. You could try
var fileName = url.Segments.Last(seg => seg.Contains("."));
to get the last segment with a dot in.

You should define a list of extensions, like .jpg, .png .gif (all files types you are expecting).
Convert your url to string (if it isnt already) and try to find the index of the extension. You do now know the position of the file name and whether there is an file name. remove everything after the file name.
now find a "/" token, and remove the part before (and including) the "/" , repeat this untill you can no longer find "/" (for example with a while function).
more information on how to do this can be found here

static string getFileName(string url) {
string[] arr = url.Split('/');
return arr[arr.Length - 1];
}

Related

Defining folder path

I have a rather curious problem.
I have this code (written by someone else). It is suppose to create couple of folders withing each other upon clicking on a specific button. It uses this:
string directoryCrate = "/" + comboIndustry.Text + "/" + comboCustomerName.Text + "/"
Now, as you see, the separator for the folders are "/". But later in the code I need to have the full path of the folder which is c:\projects and then the path to the new folder which is /Industry/Customer/...
So if I want to get the address in the clipboard it would be something like this: C"\projects/Industry/customer/... and obviously I cannot open this address in explorer! For some reason the method won't accept "\" when I try. I am quite confused. Can anyone help?
You can use
System.IO.Path.DirectorySeparatorChar
To get the standard directory separation char for your system. Also, if you try to do a replace, make sure to start the string with an # so it doesn't parse the backslashes or else escaping them as:
string backslash = #"\";
string anotherBackslash = "\\";
Try this:
string path = System.IO.Path.Combine(#"C:\Projects", directoryCrate)
string fullPath = System.IO.Path.GetFullPath(path)
or combine it into one statement.
string fullPath = System.IO.Path.GetFullPath(System.IO.Path.Combine(#"C:\Projects", directoryCrate))
Either of the above two should give you the complete path with backslashes.

How to get URL of a resource in visual studio c#?

I am making a simplePlayer WindowsForm. In order for the video to play i need to provide the url
axWindowsMediaPlayer1.URL = #"C:\Users\Stephan\Desktop\trasa-1250.wmv";
Now i need to either use relative paths or add them as a resource and get the url for that resource but i don't know how to do that:
wplayer.URL = Resources.trasa_1250.
I've tried using
axWindowsMediaPlayer1.URL = #"~\trasa-1250.wmv";
and
axWindowsMediaPlayer1.URL = #".\trasa-1250.wmv";
but printing #"~\trasa-1250.wmv"; and #.\trasa-1250.wmv"; prints them as they are without replacing the ~ or the .
To get the absolute path for a file, by supplying a name relative to the current directory, you can use:
string filename = "trasa-1250.wmv";
string path = Path.GetFullPath(filename);
For completeness sake, to create an actual Url from this:
string url = new Uri(path).AbsoluteUri;
You can't create a Url to an embedded resource, unless you program the player to accept a custom Url scheme (to allow, for instance, "resource://assemblyName.namespace.resourceName") and process it correctly.
A common alternative is to let the caller provide the Stream from which to read the media - and let them decide on how to access the resource.
Here is a tutorial that will help:
https://www.youtube.com/watch?v=nF-HYoTurc8
You could also get the URL like this:
Uri MyUri = new Uri(#"/Resources/trasa-1250.wmv", UriKind.Relative);

Copy and paste a file programmaticaly

Question Background:
I need to copy and paste (move) a file from one folder location to another.
Issue:
The File.Copy method of System.IO requires the that both parameters are of known file locations. I only know one file path location - in this case localDevPath. localQAPath is the folder path where I want the copied file to be moved too.
string localDevPath = #"C:\Folder1\testFile.cs";
string localQaPath = #"C:\Folder2\";
File.Copy(localDevPath, localQaPath);
Can anyone tell me how to go about carrying out this 'copy and paste' method I'm trying to implement.
string localDevPath = #"C:\Folder1\testFile.cs";
string localQaPath = #"C:\Folder2\";
FileInfo fi = new FileInfo(localDevPath);
fi.MoveTo(Path.Combine(localQaPath, fi.Name));
Assuming that these are user-provided paths and you can't simply include the filename in the second path, then you need to extract the last path element from localDevPath and then add it to localQaPath. You could probably do that with Path.GetFilename.
I'm guessing the issue here is that the filename is variable, in which case, you could do something like this to extract the filename from the full path of localDevPath:
string localDevPath = #"C:\Folder1\testFile.cs";
string localQaPath = #"C:\Folder2\";
string[] tokens = localDevPath.Split(#"\");
localQaPath += tokens[tokens.Length-1];
File.Copy(localDevPath, localQaPath);
Documentation on File.Copy is on MSDN. There is an overload that accepts a boolean, to allow overwriting if there is a naming conflict.
If what you want to do is move the file from one location to another, the method you are looking for is MoveTo. It is a method of the FileInfo class. There is a very complete example in the MSDN Library here: FileInfo.MoveTo Example

Managing absolute path and full path

I've created a small program wich can read a .txt file.
This file contains a link to another file in this format new_file.txt
The goal is to return the path of the new file, so basically I'm doing this :
String newFileName = getFileName();
int index = oldFilePath.lastIndexOf('\\');
String path = oldFilePath.substring(0, index + 1);
String newFilePath = path + newFileName;
return newFilePath;
For example :
The first file I opened is : C:\a\b\c\oldFile.txt
In this file I found newFile.txt
So the new path will be : C:\a\b\c\newFile.txt
Nice, but what If I find something like this :
..\ or .\.\ or ...
Is there any way to automate this mess ?
Thanks
In C#/.Net you have the rather cool Path class.
You can use Path.GetFullPath( string pathname ) to resolve paths e.g. with \..\ etc in them.
Use Path.GetDirectory(), Path.GetFileName(), Path.GetFileNameWithoutExtension() & Path.GetExtension() to pull names apart and Path.Combine() to put them back together again.
You've tagged this as java as well as c#
In java look at FileNameUtils http://commons.apache.org/io/apidocs/org/apache/commons/io/FilenameUtils.html
The normalize method should help

Uri.AbsolutePath messes up path with spaces

In a WinApp I am simply trying to get the absolute path from a Uri object:
Uri myUri = new Uri(myPath); //myPath is a string
//somewhere else in the code
string path = myUri.AbsolutePath;
This works fine if no spaces in my original path. If spaces are in there the string gets mangled; for example 'Documents and settings' becomes 'Documents%20and%20Setting' etc.
Any help would be appreciated!
EDIT:
LocalPath instead of AbsolutePath did the trick!
This is the way it's supposed to be. That's called URL encoding. It applies because spaces are not allowed in URLs.
If you want the path back with spaces included, you must call something like:
string path = Server.URLDecode(myUri.AbsolutePath);
You shouldn't be required to import anything to use this in a web application. If you get an error, try importing System.Web.HttpServerUtility. Or, you can call it like so:
string path = HttpContext.Current.Server.URLDecode(myUri.AbsolutePath);
It's encoding it as it should, you could probably UrlDecode it to get it back with spaces, but it's not "mangled" it's just correctly encoded.
I'm not sure what you're writing, but to convert it back in asp.net it's Server.UrlDecode(path). You also might be able to use LocalPath, rather than AbsolutePath, if it's a Windows app.
Just use uri.LocalPath instead
Uri also has a couple of static methods - EscapeDataString and EscapeUriString.
Uri.EscapeDataString(uri.AbsolutePath) also works
Use HttpUtility:
HttpUtility.UrlDecode(uri.AbsolutePath)

Categories

Resources