Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Get filename out of a string

Posted on 2006-11-03
4
Medium Priority
?
217 Views
Last Modified: 2010-04-16
I have a the following string:

C:\Documents and Settings\test\My Documents\My Pictures\Logo2.gif

How do I just get the

Logo2.gif

out of the string

I'm using

strFileNamePath.Substring(strFileNamePath.LastIndexOf("\\"), strFileNamePath.Length);

But I get an error all the time

"Index and length must refer to a location within the string. Parameter name: length "

Many thanks
0
Comment
Question by:mousemat24
  • 2
4 Comments
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 2000 total points
ID: 17869252
Use:

            string fullpath = @"C:\Documents and Settings\test\My Documents\My Pictures\Logo2.gif";
            string filename = System.IO.Path.GetFileName(fullpath);
0
 

Author Comment

by:mousemat24
ID: 17869303
Thanks carl_tawn !! Quick quetion why dosnt my ver work?

strFileNamePath.Substring(strFileNamePath.LastIndexOf("\\"), strFileNamePath.Length);

I cant see why that should cause an error?
0
 
LVL 13

Expert Comment

by:joechina
ID: 17869333
Try

strFileNamePath.Substring(strFileNamePath.LastIndexOf("\\") + 1);


Or Try the following two ways

1)
result = (new FileInfo(strFileNamePath)).Name;

2)
result = Regex.Match(strFileNamePath, "[^\\\\]+$").Value;

0
 
LVL 13

Expert Comment

by:joechina
ID: 17869350
strFileNamePath.Length is the length of both filename and path.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Integration Management Part 2

916 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question