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怎么处理?

解决方案 »

  1.   

    if ((ch =='\')||(ch =='/')||(ch ==':')) 就是这里?
      

  2.   

    用下面代码:
    if ((ch ==@'\')||(ch ==@'/')||(ch ==@':'))
      

  3.   

    你不用自己写,有现成的
    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 ''
      

  4.   

    要查找这些字符所在位置,直接使用IndexOf方法或LastIndexOf方法即可,不需要那么麻烦。