Parsing Image Path in ImageResizer - c#

I'm resizing an image dynamically thus:
ImageJob i = new ImageJob(file, "~/eventimages/<guid>_<filename:A-Za-z0-9>.<ext>",
new ResizeSettings("width=200&height=133&format=jpg&crop=auto"));
i.Build();
I'm attempting to store the image relative URL in the DB. The i.FinalPath property gives me:
C:\inetpub\wwwroot\Church\eventimages\56b640bff5ba43e8aa161fff775c5f97_scenery.jpg
How can I obtain just the image filename - best way to parse this?
Desired string: /eventimages/56b640bff5ba43e8aa161fff775c5f97_scenery.jpg

something like below,
var sitePath = MapPath(#"~");
var relativePath= i.FinalPath.Replace(sitePath, "~");

Just use Regular expressions
Regex.Match
Create you pattern and extract desired value
string input = "C:\\inetpub\\wwwroot\\Church\\eventimages\\56b640bff5ba43e8aa161fff775c5f97_scenery.jpg";
Match match = Regex.Match(input, #"^C:\\[A-Za-z0-9_]+\\[A-Za-z0-9_]+\\[A-Za-z0-9_]+\\([A-Za-z0-9_]+\\[A-Za-z0-9_]+\.jpg)$", RegexOptions.IgnoreCase);
if (match.Success)
{
// Finally, we get the Group value and display it.
string path = match.Groups[1].Value.Replace("\\", "/");
}

Here is what I use in a utility method:
Uri uri1 = new Uri(i.FinalPath);
Uri uri2 = new Uri(HttpContext.Current.Server.MapPath("/"));
Uri relativeUri = uri2.MakeRelativeUri(uri1);
(stolen from someone else... can't remember who, but thanks)

Related

C# substring after specific sign

how can I get a value of the string after last'/'
string path=http://localhost:26952/Images/Users/John.jpg
I would like to have as a result something like :
John.jpg
I think using Path.GetFileName method is a better way instead of string manipulation.
string path = "http://localhost:26952/Images/Users/John.jpg";
var result = Path.GetFileName(path);
Console.WriteLine(result); // John.jpg
Split by '/' and get the last part:
var url = "http://localhost:26952/Images/Users/John.jpg";
var imageName = url.Split('/').Last();

Add a directory name to a URL address using C#

I have a textbox where users can paste a URL address. I want to add a directory name to the URL before saving it in the database.
<asp:TextBox ID="urlTextbox" runat="server"></asp:TextBox>
Code behind
TextBox url = urlTextbox as TextBox;
string urlString = urlTextbox.Text;
Let's say the urlString = "mydomain.com/123456". I want to replace it with "mydomain.com/directory/123456". mydomain.com/directory is the same for all the URLs. The last part "123456" changes only.
Thank you
I'd suggest seeing if your needs are met with the UriBuilder class.
UriBuilder url = new UriBuilder(urlTextbox.Text);
Now you can use the various properties to change your url.
string formattedUrl = string.Format("{0}://{1}/directory/{2}", url.Scheme, url.Host, url.Path);
A better idea is to adjust the URL with another / same UriBuilder as noted by Jared.
UriBuilder url = new UriBuilder(urlTextbox.Text);
url.Path = string.Format("directory/{0}", url.Path);
Use this object as a Uri by simply doing this
Uri formattedUrl = url.Uri;
Or convert to a string if needed.
string formattedUrl = url.ToString();
You can also use Uri.TryParse(...) to verify if it's a valid URL being entered into the text box.
To get the individual query parameters, you can look at the Uri object.
UriBuilder url = new UriBuilder("mydomain.com/123456?qs=aaa&bg=bbb&pg=ccc");
url.Path = string.Format("directory/{0}", url.Path);
Uri formattedUrl = url.Uri;
string queryString = formattedUrl.Query;
// parse the query into a dictionary
var parameters = HttpUtility.ParseQueryString(queryString);
// get your parameters
string qs = parameters.Get("qs");
string bg = parameters.Get("bg");
string pg = parameters.Get("pg");
You can use string functions Split and Join to achieve your result. An example code is shown below
List<string> parts = urlString.Split(new char[] { '/'}).ToList();
parts.Insert(parts.Count - 1, "directory");
urlString = string.Join("/", parts);
This is one way of doing. Split the urlString using .split() function.
string[] parts = urlString.Split('/');
parts[parts.Length-1] will have that number. Append it to the string you want.
I'd do something like this:
//Assuming the address in urlString has the format mydomain.com/123456
string[] urlParts = urlString.Split('/');
string directory = "directory";
string finalUrl = urlParts[0] + "/" + directory + "/" + urlParts[1];
Be careful if the address has other "/" characters, like if preceded by http:// or something like that.
Hope it helps.
Simply use concatenation:
save in a temporary string
temp="mydomain.com/directory/"
and save the changing part in another string like
temp2="123456"
now concatenate both temp1 and temp2 like below.
urlString=temp1+temp2;

Replace specific string in large string

I'm writing a small WPF Application which helps my company to update costumer projects. I have a list of SQL-Files which I have to execute. Now these scripts are always written with a "USE [Insert_Database]". I read the whole content of a script into a string, but my Replace method doesn't seem to do anything.
string content = File.ReadAllText(file);
content.Replace("Insert_Database", Database.Name);
SqlScriptsList.Add(new SqlScriptModel {Name = Path.GetFileName(file), Path = file, ScriptContent = content});
String.Replace returns the modified string, so it should be:
content = content.Replace(....);
This method does not modify the value of the current instance.
Instead, it returns a new string in which all occurrences of oldValue
are replaced by newValue.
You can use replace function as follow on strings
str = str.Replace("oldstr","newstr");
if oldstr is found in the str then it will be replaced by new str
You aren't using new value when you call replace.
string content = File.ReadAllText(file);
content = content.Replace("Insert_Database", Database.Name);
SqlScriptsList.Add(new SqlScriptModel {Name = Path.GetFileName(file), Path = file, ScriptContent = content});
for reference: the MSDN doc for replace https://msdn.microsoft.com/en-us/library/system.string.replace(v=vs.110).aspx

The fastest way to trim string in C#

I need to trim paths in million strings like this:
C:\workspace\my_projects\my_app\src\my_component\my_file.cpp
to
src\my_component\my_file.cpp
I.e. remove absolute part of the path, what is the fastest way to do that?
My try using regex:
Regex.Replace(path, #"(.*?)\src", ""),
I wouldn't go with regex for this, use the plain old method.
If the path prefix is always the same:
const string partToRemove = #"C:\workspace\my_projects\my_app\";
if (path.StartsWith(partToRemove, StringComparison.OrdinalIgnoreCase))
path = path.Substring(partToRemove.Length);
If the prefix is variable, you can get the last index of \src\:
var startIndex = path.LastIndexOf(#"\src\", StringComparison.OrdinalIgnoreCase);
if (startIndex >= 0)
path = path.Substring(startIndex + 1);
define the regex with a new and reuse it
there is a (significant) cost to creating the regex
string input = "This is text with far too much " +
"whitespace.";
string pattern = "\\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
I'm not sure if you need speed here, but if you always get the full path, you could do a simple .Substring()
var path = #"C:\workspace\my_projects\my_app\src\my_component\my_file.cpp";
Console.WriteLine(path.Substring(32));
However, I think you should sanitize your input first; in this case, the Uri class could do the parsing step:
var root = #"C:\workspace\my_projects\my_app\";
var path = #"C:\workspace\my_projects\my_app\src\my_component\my_file.cpp";
var relative = new Uri(root).MakeRelativeUri(new Uri(path));
Console.WriteLine(relative.OriginalString.Replace("/", "\\"));
Notice here the Uri will change the \ with a /: that's the .Replace reason.
Cant think any faster than this
path.Substring(33);
What is before src is constant. and it starts from index 33.
C:\workspace\my_projects\my_app\src\my_component\my_file.cpp
^
How ever if its not always constant. you can find it once. and do the rest inside loop.
int startInd = path.IndexOf(#"\src\") + 1;
// Do this inside loop. 1 million times
path.Substring(startInd);
If your files will all end in "src/filename.ext" you could use the Path class in the .NET framework for it and get around all caveats you could have with pathes and filenames:
result = "src\" + Path.GetFileName(path);
So you should first double-check that the conversion is the thing that takes to long.

RegEx to extract a sub level from url

i have the following set of Urls:
http://test/mediacenter/Photo Gallery/Conf 1/1.jpg
http://test/mediacenter/Photo Gallery/Conf 2/3.jpg
http://test/mediacenter/Photo Gallery/Conf 3/Conf 4/1.jpg
All i want to do is to extract the Conf 1, Conf 2,Conf 3 from the urls, the level after 'Photo Gallery' (Urls are not static, they share common level which is Photo Gallery)
Any help is appreciated
Is it necessary to use Regex? You can get it without using Regex like this
string str= #"http://test/mediacenter/Photo Gallery/Conf 1/1.jpg";
var z=qq.Split('/')[5];
or
var x= new Uri(str).Segments[3];
This ought to do you:
var s = #"http://test/mediacenter/Photo Gallery/Conf 11/1.jpg";
var regex = new Regex(#"(Conf \d*)");
var match = regex.Match(s);
Console.WriteLine(match.Groups[0].Value); // Prints a
Of course, you'd have to be confident the 'Conf x' (where x is a number) wasn't going to be elsewhere in the URL.
This will improve it slightly by stripping off multiple folders (Conf 3/Conf 4) in your example.
var regex = new Regex(#"((Conf \d*/*)+)");
It leaves the trailing / though.
No need for regex.
string testCase = "http://test/mediacenter/Photo Gallery/Conf 1/1.jpg";
string urlBase = "http://test/mediacenter/Photo Gallery/";
if(!testCase.StartsWith(urlBase))
{
throw new Exception("URL supplied doesn't belong to base URL.");
}
Uri uriTestCase = new Uri(testCase);
Uri uriBase = new Uri(urlBase);
if(uriTestCase.Segments.Length > uriBase.Segments.Length)
{
System.Console.Out.WriteLine(uriTestCase.Segments[uriBase.Segments.Length]);
}
else
{
Console.Out.WriteLine("No child segment...");
}
Try a RegEx like this.
Conf[^\/]*
This should give you all "Conf" Parts of the URLs.
I hope that helps.

Categories