private void button1_Click(object sender, EventArgs e)
{
//InitialDirectory:对话框的初始目录
//Filter: 获取或设置当前文件名筛选器字符串,例如,"文本文件(*.txt)|*.txt|所有文件(*.*)||*.*"
//FilterIndex 在对话框中选择的文件筛选器的索引,如果选第一项就设为1
//RestoreDirectory 控制对话框在关闭之前是否恢复当前目录
//FileName:第一个在对话框中显示的文件或最后一个选取的文件
//Title 将显示在对话框标题栏中的字符
//AddExtension 是否自动添加默认扩展名
//CheckPathExists 在对话框返回之前,检查指定路径是否存在
//DefaultExt 默认扩展名
//DereferenceLinks 在从对话框返回前是否取消引用快捷方式
//ShowHelp 启用"帮助"按钮
//ValiDateNames 控制对话框检查文件名中是否不含有无效的字符或序列
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "";//注意这里写路径时要用c:\\而不是c:\
openFileDialog.Filter = "文本文件|*.txt*|图片|*.JPG|所有文件|*.*";
openFileDialog.RestoreDirectory = true;
openFileDialog.FilterIndex = 3;
openFileDialog.Title = "图片选择";
string fPath = null;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
fPath = openFileDialog.FileName;
textBox1.Text = fPath;
}
// 获取当前运行程序的目录
string fileDir = Environment.CurrentDirectory;
textBox2.AppendText("当前程序目录:" + fileDir + "\r\n");
bool result = Directory.Exists(Path.GetDirectoryName(fPath));//判断这个路径下是否有文件夹
if (result)
{
textBox2.AppendText("获取文件的全路径:" + Path.GetFullPath(fPath) + "\r\n"); //-->C:\JiYF\BenXH\BenXHCMS.xml
textBox2.AppendText("获取文件所在的目录:" + Path.GetDirectoryName(fPath) + "\r\n"); //-->C:\JiYF\BenXH
textBox2.AppendText("获取文件的名称含有后缀:" + Path.GetFileName(fPath) + "\r\n"); //-->BenXHCMS.xml
textBox2.AppendText("获取文件的名称没有后缀:" + Path.GetFileNameWithoutExtension(fPath) + "\r\n"); //-->BenXHCMS
textBox2.AppendText("获取路径的后缀扩展名称:" + Path.GetExtension(fPath) + "\r\n"); //-->.xml
}
else
{
MessageBox.Show("路径有误");
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox2.Text = "";
//C: \Users\tang\Pictures\Saved Pictures ;*.jpeg;*.png;*.gif;*.bmp
string folderPath = Path.GetDirectoryName(textBox1.Text);
List<string> images = new List<string> {".jpg",".bmp",".png" };
string[] fileNames = Directory.GetFiles(folderPath,"*.*", SearchOption.TopDirectoryOnly);
label3.Text = fileNames.Length.ToString();
// 输出找到的文件名
int index = 1;
foreach (string fileName in fileNames)
{
string ext = Path.GetExtension(fileName);
string newName = textBox3.Text;
string newFileName = Path.GetDirectoryName(fileName)+"\\"+newName+index.ToString()+ ext;
if (images.Contains(ext))
{
textBox2.AppendText(Path.GetFileName(fileName)+"\r\n");
}
else
{
textBox2.AppendText("非图片类型"+Path.GetFileName(fileName) + "\r\n");
}
}
label3.Text = "OK";
}
private void button3_Click(object sender, EventArgs e)
{
label3.Text = "改变";
}
C#-OpenFileDialog类使用、Path类、Directory类
最新推荐文章于 2025-03-18 09:22:32 发布