using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace CS00020_2
{
class TestOut
{
static void SplitPath(string path, out string dir, out string name)
{
int i = path.Length;
//以下计算路径的节点
while (i > 0)
{
char ch = path[i - 1];
if ((ch =='\')||(ch =='/')||(ch ==':'))
break;
else
i--;
}
dir = path.Substring(0, i); //在path的字符串中从第0个开始取出前i个字符,并赋值到dir上
name = path.Substring(i); //在path的字符串中取出后i个字符,并赋值到name上
}
static void Main(string[] args)
{
string dir, name;
SplitPath("c:\"learncs\"hello.txt", out dir, out name);
Console.WriteLine(dir);
Console.WriteLine(name);
}
}
}一段小代码加红部分为什么会出错呢?字符char怎么处理?
if ((ch ==@'\')||(ch ==@'/')||(ch ==@':'))
Path.GetDirectoryName和Path.GetFileName
string fileName = @"C:\mydir\myfile.ext";
string path = @"C:\mydir\";
string rootPath = @"C:\";
string directoryName;directoryName = Path.GetDirectoryName(fileName);
Console.WriteLine("GetDirectoryName('{0}') returns '{1}'",
fileName, directoryName);directoryName = Path.GetDirectoryName(path);
Console.WriteLine("GetDirectoryName('{0}') returns '{1}'",
path, directoryName);directoryName = Path.GetDirectoryName(rootPath);
Console.WriteLine("GetDirectoryName('{0}') returns '{1}'",
rootPath, directoryName);
/*
This code produces the following output:GetDirectoryName('C:\mydir\myfile.ext') returns 'C:\mydir'
GetDirectoryName('C:\mydir\') returns 'C:\mydir'
GetDirectoryName('C:\') returns ''*/string fileName = @"C:\mydir\myfile.ext";
string path = @"C:\mydir\";
string result;result = Path.GetFileName(fileName);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
fileName, result);result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
path, result);// This code produces output similar to the following:
//
// GetFileName('C:\mydir\myfile.ext') returns 'myfile.ext'
// GetFileName('C:\mydir\') returns ''