C# OpenFileDialog设置默认打开的文件路径

本文介绍了一个使用C#编写的简单应用程序,该程序能够创建并管理两个不同类型的日志文件夹及对应的日志文件,并提供了打开这些日志文件的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个功能我的使用场景是这个样子的:tool运行的时候保存了几种log,查看不同的问题需要打开不同的log,为不同log放在了不同的文件夹下面。
好了,直接上代码了:

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

namespace openlog
{
    public partial class Form1 : Form
    {
        private string logPath1, logPath2;
        public Form1()
        {
            InitializeComponent();
            FileStream fs;            
            logPath1 = System.Environment.CurrentDirectory.ToString()/*获取软件运行时的路径*/ + @"\log\log1\";//如果需要设置特定的路径logPath1=@"C:\Program Files\";
            logPath2 = System.Environment.CurrentDirectory.ToString() + @"\log\log2\";
            if (!Directory.Exists(logPath1))
            {
                Directory.CreateDirectory(logPath1);
                using (fs = new FileStream(logPath1 + "log1.txt", FileMode.CreateNew)) { }//创建相对于软件运行目录的路径以及文件名
            }
            if (!Directory.Exists(logPath2))
            {
                Directory.CreateDirectory(logPath2);
                using (fs = new FileStream(logPath2 + "log2.txt", FileMode.CreateNew)) { }
            }                       
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.InitialDirectory = logPath1;//设置打开路径的目录
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                MessageBox.Show("你打开的文件路径为" + openFileDialog1.FileName.ToString());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog2 = new OpenFileDialog();
            openFileDialog2.InitialDirectory = logPath2;
            if (openFileDialog2.ShowDialog() == DialogResult.OK)
            {
                MessageBox.Show("你打开的文件路径为" + openFileDialog2.FileName.ToString());
            }
        }
    }
}

源码下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值