Path

The static Path class defines methods and fields for working with paths and filenames.


using System;
using System.IO;
using System.Linq;
using System.Text;

class Program
{
    static void Main()
    {
        string dir = @"c:\g";
        string file = "myfile.txt";
        string path = @"c:\g\myfile.txt";

        Directory.SetCurrentDirectory(@"k:\demo");
        Directory.GetCurrentDirectory();
        Path.IsPathRooted(file);
        Path.IsPathRooted(path);
        Path.GetPathRoot(path);
        Path.GetDirectoryName(path);
        Path.GetFileName(path);
        Path.GetFullPath(file);
        Path.Combine(dir, file);

    }
}

File extensions


using System;
using System.IO;
using System.Linq;
using System.Text;

class Program
{
    static void Main()
    {
        string file = "myfile.txt";

        Path.HasExtension(file);
        Path.GetExtension(file);
        Path.GetFileNameWithoutExtension(file);
        Path.ChangeExtension(file, ".log");


    }
}

Separators and characters:


using System;
using System.IO;
using System.Linq;
using System.Text;

class Program
{
    static void Main()
    {
        Console.WriteLine(Path.AltDirectorySeparatorChar);
        Console.WriteLine(Path.PathSeparator);
        Console.WriteLine(Path.VolumeSeparatorChar);
        Console.WriteLine(Path.GetInvalidPathChars());
        Console.WriteLine(Path.GetInvalidFileNameChars());
    }
}

The output:

 
/
;
:
"<>|
  

Temporary files:


using System;
using System.IO;
using System.Linq;
using System.Text;

class Program
{
    static void Main()
    {
        Console.WriteLine(Path.GetTempPath());
        Console.WriteLine(Path.GetRandomFileName());
        Console.WriteLine(Path.GetTempFileName());
    }
}

The output:


C:\Users\abc\AppData\Local\Temp\
1clkm1ro.csc
C:\Users\abc\AppData\Local\Temp\tmp14D0.tmp
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.