Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I use a regular expression on this file path?

Tags:

c#

I have to strip a file path and get the parent folder.

Say my path is

\\ServerA\FolderA\FolderB\File.jpg

I need to get

  1. File Name = File.jog

  2. Folder it resides in = FolderB

  3. And parent folder = FolderA

I always have to go 2 levels up from where the file resides.

Is there an easier way or is a regular expression the way to go?

like image 799
uno Avatar asked Apr 20 '10 19:04

uno


People also ask

Where can you use regex?

Regular expressions are used in search engines, in search and replace dialogs of word processors and text editors, in text processing utilities such as sed and AWK, and in lexical analysis.

What does \\ mean in regex?

\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \. html?\ ' .

What is file regex?

A regular expression (regex) is a search pattern that locates files and folders containing a specific sequence of characters by comparing that sequence to absolute file paths on your device. You can use the power of regular expressions to fine-tune and allow for more complex backup file exclusion rules.

What do you use in a regular expression to match any 1 character or space?

Use square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.


1 Answers

FileInfo is your friend:

using System;
using System.IO;

class Test
{
    static void Main(string[] args)
    {
        string file = @"\\ServerA\FolderA\FolderB\File.jpg";
        FileInfo fi = new FileInfo(file);
        Console.WriteLine(fi.Name);                  // Prints File.jpg
        Console.WriteLine(fi.Directory.Name);        // Prints FolderB
        Console.WriteLine(fi.Directory.Parent.Name); // Prints FolderA
    }
}
like image 190
Jon Skeet Avatar answered Sep 25 '22 02:09

Jon Skeet