C# Path类静态方法汇总及实例演示

1、定义
using System.IO;

Path类的静态方法汇总:

ChangeExtension 更改路径字符串的扩展名。


Combine(String()) 将字符串数组组合成一个路径。

Combine(String, String) 将两个字符串组合成一个路径。

Combine(String, String, String) 将三个字符串组合成一个路径。

Combine(String, String, String, String) 将四个字符串组合成一个路径。


GetDirectoryName 返回指定路径字符串的目录信息。

GetExtension 返回指定的路径字符串的扩展名。

GetFileName 返回指定路径字符串的文件名和扩展名。

GetFileNameWithoutExtension 返回不具有扩展名的指定路径字符串的文件名。

GetFullPath 返回指定路径字符串的绝对路径。


GetInvalidFileNameChars 获取包含不允许在文件名中使用的字符的数组。

GetInvalidPathChars 获取包含不允许在路径名中使用的字符的数组。

GetPathRoot 获取指定路径的根目录信息。

GetRandomFileName 返回随机文件夹名或文件名。

GetTempFileName 创建磁盘上唯一命名的零字节的临时文件并返回该文件的完整路径。

GetTempPath 返回当前用户的临时文件夹的路径。

HasExtension 确定路径是否包括文件扩展名。

IsPathRooted 获取指示指定的路径字符串是否包含根的值。

2、常用实例
1)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
**using System.IO;**
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace path
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string filePath = @"D:\file.txt";

            textBox1.Text=Path.GetExtension(filePath);//GetExtension 返回指定的路径字符串的扩展名
            textBox2.Text = Path.ChangeExtension(filePath, "bak");// ChangeExtension 更改路径字符串的扩展名;仅更改路径字符串中的扩展名,并不会改变实际文件的扩展名或者目录

            textBox3.Text = Path.GetFileName(filePath);//GetFileName()方法:从路径字符串中得到文件名(带扩展名)
            textBox4.Text = Path.GetFileNameWithoutExtension(filePath);//GetFileNameWithoutExtension()方法,从路径字符串中得到文件名(不带扩展名)
            textBox5.Text = Path.GetFullPath(filePath);//GetFullPath()方法,从文件字符串中得到包括文件名和扩展名的全路径名。
            textBox6.Text = Path.GetDirectoryName(filePath);//GetDirectoryName()方法,得到文件的文件夹路径。

            //Combine()方法,合并两个文件路径字符串。
            string Str1 = @"C:\Users\Administrator\";

            string Str2 = @"Desktop\file.txt";


            textBox7.Text = Path.Combine(Str1, Str2);
         

        }
    }
}

C# Path类静态方法汇总及实例演示_第1张图片

你可能感兴趣的:(.NET)