9.14 Work with Relative Paths


Problem

You want to set the current working directory so that you can use relative paths in your code.

Solution

Use the static GetCurrentDirectory and SetCurrentDirectory methods of the System.IO.Directory class.

Discussion

Relative paths are automatically interpreted in relation to the current working directory. You can retrieve the current working directory by calling Directory.GetCurrentDirectory or change it using Directory.SetCurrentDirectory . In addition, you can use the static GetFullPath method of the System.IO. Path class to convert a relative path into an absolute path using the current working directory.

Here's a simple example that demonstrates these concepts:

 using System; using System.IO; public class RelativeDirTest {     private static void Main() {         Console.WriteLine("Using: " + Directory.GetCurrentDirectory());         Console.WriteLine("The relative path 'file.txt' " +           "will automatically become: '" +            Path.GetFullPath("file.txt") + "'");         Console.WriteLine();         Console.WriteLine("Changing current directory to c:\");         Directory.SetCurrentDirectory("c:\");         Console.WriteLine("Now the relative path 'file.txt' " +           "will automatically become '" +           Path.GetFullPath("file.txt") + "'");         Console.ReadLine();     } } 

The output for this example might be the following (if you run the application in the directory c:\temp):

 Using: c:\temp The relative path 'file.txt' will automatically become 'c:\temp\file.txt' Changing current directory to c:\ The relative path 'file.txt' will automatically become 'c:\file.txt' 
Note  

If you use relative paths, it's recommended that you set the working path at the start of each file interaction. Otherwise, you could introduce unnoticed security vulnerabilities that could allow a malicious user to force your application into accessing or overwriting system files by tricking it into using a different working directory.




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net