How to remove end of string (fileName) using substring? - c#

I know I must use Substring to remove, but I dont know how to do this. I need to remove end of string like this
from
"C:\\Users\\myname\\Pictures\\shoeImage.jpg"
to
"C:\\Users\\myname\\Pictures"

Use the methods of the System.IO.Path class instead, in specific GetDirectoryName.

You can use Path.GetDirectoryName method.
Returns the directory information for the specified path string.
Console.WriteLine(Path.GetDirectoryName("C:\\Users\\myname\\Pictures\\shoeImage.jpg"));
It returns this;
C:\Users\myname\Pictures
Here a DEMO.
With String.SubString method, you can use it like;
string path = "C:\\Users\\myname\\Pictures\\shoeImage.jpg";
Console.WriteLine(path.Substring(0, path.LastIndexOf(#"\")));

You should use FileInfo in such scenarios -
FileInfo info = new FileInfo("C:\\Users\\myname\\Pictures\\shoeImage.jpg");
string name = info.DirectoryName;
OR
Path.GetDirectoryName("C:\\Users\\myname\\Pictures\\shoeImage.jpg");

If you want to substring it:
var subString = yourString.SubString(0, yourString.LastIndexOf('\\'));

Related

Get arguments and file name from specific path

I'm trying to extract argument and file name from path like below:
C:\Users\user\Desktop\foo.exe foo://action/bar
I tried to use Path.GetFileName but since argument contains directory separators, it returns bar instead of foo.exe
Is there any way to get argument and file name?
You can get the command line argument from the string [] args passed to the Main method.
Or you can use the static method Environment.GetCommandLineArgs https://msdn.microsoft.com/en-us/library/system.environment.getcommandlineargs(v=vs.110).aspx
Use LastIndexOf to reverse-search the string for the backslash, then Substring to grab everything beyond that:
int i = path.LastIndexOf(#"\");
return (i > -1 && i < path.Length) ? path.Substring(i + 1) : string.Empty;
If you need to separate the filename and argument, use IndexOf to look for the space or Split the result on the space character.

substring from specific point of the string(from reverse side )

I wanted to substring from special point.
abcdef.png
I want
.png
Here i tried
string str = "abcdef.png";
str = str.Substring(0, str.Length - 4);
but then only shows the abcdef only BUT i want .png part
Just use the overload which takes a single parameter - the start point:
str = str.Substring(str.Length - 4);
Or better, use a method designed to get the extension of a filename - Path.GetExtension:
string extension = Path.GetExtension(str);
You can use Path.GetExtension method instead of substring.
string str = "abcdef.png";
string ext = Path.GetExtension(str); // .png
It seems you're dealing with file names, Use Path.GetExtension method for this purpose.
You need to pass str.Length - 4 as the first (and only) parameter, not as the second parameter:
str = str.Substring(str.Length - 4);
The way your code had it, you got a substring starting at zero, and containing str.Length - 4 characters.
If you want to take just the dot and the extension, use
str = str.Substring(str.LastIndexOf('.'));
expression.
If you want the extension of a filename use Path.GetExtension(str). Much easier.
http://msdn.microsoft.com/en-us/library/system.io.path.getextension(v=vs.110).aspx
try below code it will return the extension of file.
string extension = Path.GetExtension(str);

Replace URL in a string

I'm a beginner in C# and I have the following string,
string url = "svn1/dev";
along with,
string urlMod = "ato-svn3-sslv3.of.lan/svn/dev"
I want to replace svn1 in url with "ato-svn3-sslv3.of.lan"
Although your question still has some inconsistent statements, I believe String.Replace is what you are looking for:
http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx
url = url.Replace("svn1","ato-svn3-sslv3.of.lan");
Strings are immutable so you need to assign the return value to a variable:
string replacement = "ato-svn3-sslv3.of.lan";
url = url.Replace("svn1", replacement);
You can use the string method replace.
url = url.Replace("svn1", urlMod)
I think you need this:
string url = "svn1/dev";
string anotherUrl = "ato-svn3-sslv3.of.lan/svn/dev";
string toBeReplaced = anotherUrl.Split('/')[0];
url = url.Replace("svn1", toBeReplaced);
It uses split method and replace method.

C# Cannot implicitly convert type 'string' to 'string[]' within an if else statement

I am trying to read a string into an array and I get the error "Cannot implecitly convert type 'string' to 'string[]'.
The error occurs here:
string[] sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
My full if else statement is below:
if (!string.IsNullOrEmpty(result.Tables[0].Rows[0].Field<string>("WebHTML")))
{
string[] sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
NewsContent.Text = sepText[1];
if (!string.IsNullOrEmpty(sepText[0]))
Image1.ImageUrl = sepText[0];
else
Image1.Visible = false;
NewsTitle.Text = String.Format("{3}", Extensions.GetServerName(true), result.Tables[0].Rows[0].Field<int>("News_Item_ID"), result.Tables[0].Rows[0].Field<string>("Title").UrlFormat(), result.Tables[0].Rows[0].Field<string>("Title"));
Hyperlink1.NavigateUrl = String.Format("{0}/news/{1}/{2}.aspx", Extensions.GetServerName(true), result.Tables[0].Rows[0].Field<int>("News_Item_ID"), result.Tables[0].Rows[0].Field<string>("Title").UrlFormat());
}
else
{
Hyperlink1.Visible = false;
Image1.Visible = false;
}
Thank you for your help!
EDIT Code for URL Decode:
public static string UrlDecode(this string str)
{
return System.Web.HttpUtility.UrlDecode(str);
}
result.Tables[0].Rows[0].Field<string>("WebHTML") is going to give you the value of the WebHTML field in the first row in the first table which is a single string rather than a string[].
You may want to show your code for UrlDecode() since it looks like a custom implementation rather than one of the built-in framework versions.
You also declare the UrlDecode method to take a string as a parameter and return a string. Remember, a string is not the same thing as a string array.
It seems that you are trying to put:
result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
which returns a string, into an array of strings.
Simply delare your sepText variable as a string rather than a string array and you should be good to go, e.g.:
string sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
Later in your code you will clearly need to read the contents of the string like this:
Image1.ImageUrl =sepText;
Assuming the UrlDecode you are using is the one from here then the result is a string and not a string[] !
UrlDecode returns a string and you are assigning it to an array.
If you want the parts you will have to use the string to create an Url object.
Url url = new Url(result.Tables[0].Rows[0].Field<string>("WebHTML"));
and then get the parts.
See: Get url parts without host
I don't think URLDecode works the way you think it works. All URLDecode does is remove URL encoding from a string. It does not return an array of strings - only the decoded value of the string you gave it.
http://msdn.microsoft.com/en-us/library/system.web.httputility.urldecode.aspx
Example: Your web browser replaces a space with %20. This changes the %20 back to a space.
That's because the result of this line is "string" and you're trying to assign it to an array since UrlDecode do not produce an array. What you probably wanted is to use a method split() to create an array of separators?

File details from a string in C#

I have a string in C#
String file="\\mserver-80\docs\somedoc.doc"
Now How do I get fileInfo from the above sting.
What I mean is,
I want to declare something like
FileInfo fInfo = new FileInfo(file);
fileExtn = fInfo.Extension;
You can also try
Path.GetExtension(file)
In C# the string should be
String file="\\\\mserver-80\\docs\\somedoc.doc";
You can also escacpe the string using the # character, which is a better alternative:
String file=#"\\mserver-80\docs\somedoc.doc";
other than that the code should work.
That code will work fine, using the FileInfo class.
Simply add
using System.IO;
However, note that the \ must be escaped as \\.
Instead, you should use an #"" string, like this:
String file = #"\\mserver-80\docs\somedoc.doc"

Categories