Converting Strings to Path in C#?
In C#, the Path
class, part of the System.IO
namespace, provides methods for working with paths. Converting strings to paths becomes important when you need to perform operations like file manipulation, navigation, or validation.
The below program shows how to convert strings into path objects. We will use the Path.Combine
method to join two strings into a path.
using System;
using System.IO;
class Program
{
static void Main()
{
// Input strings representing directory and file names
string directoryName = "C:\\MyFiles";
string fileName = "example.txt";
// Convert strings to path
string fullPath = Path.Combine(directoryName, fileName);
// Display the result
Console.WriteLine("Full Path: " + fullPath);
}
}
In this example, the Path.Combine
method takes two strings representing a directory name and a file name and combines them into a full path.
Output:
Full Path: C:\MyFiles\example.txt
Comments (0)