琐碎--选择文件夹(路径)+生产txt格式的log+数据库操作方式

记录日常工作常用到的一些方法:

在.Net中处理系统文件相关的几个类分别是File、Directory、FileInfo、DirectoryInfo、DriveInfo、FileSystemWatcher。本文介绍下这几个类的用法。

1.File类提供静态方法用来创建、移动、复制、删除文件的操作,并可以打开文件流

2.Directory类提供静态方法用来创建、移动、复制、删除目录的操作

3.FileInfo类用类实例实现创建、复制、移动、删除文件的操作

4.DirectoryInfo提供创建、移动、复制、删除目录的操作,并可以枚举子目录

5.DriveInfo可以获得windows操作系统中的磁盘信息

6.FileSystemWatcher用来监视文件或目录变化,并引发事件

7.Path类提供文件名目录名操作的静态方法

 

1 选择文件操作,并将文件的路径记录下来:

OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = false;
            ofd.Title = "请选择文件";
            ofd.Filter = "(*.*)|*.*";
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                tb1.Text = ofd.FileName;//文件的路径
            }

 

2 选择文件夹的操作,并将文件夹的路径记录下来:

FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.Description = "请选择文件夹";
            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string str = fbd.SelectedPath;//文件夹的路径
            }

 

2-1 选择路径并输入文件名称,限定类型:

string outputFilename = string.Empty;
            using (SaveFileDialog path = new SaveFileDialog())
            {
                path.Filter = @"Excel files (*.xlsx)|*.xlsx";
                path.RestoreDirectory = true;
               
                if(path.ShowDialog() == DialogResult.OK)
                {
                    outputFilename = path.FileName;
                }
            }

 

3 、生成txt格式的log:

public void WriteLog(string txt)
        {
            try
            {
                txt = DateTime.Now.ToString() + " " + txt;

                string str = System.IO.Directory.GetCurrentDirectory();
                string firstStr = str.Substring(0, 1);
                //生成文件夹
                string filesPath = firstStr + ":/倒计时日志";
                if (!Directory.Exists(filesPath))
                {
                    Directory.CreateDirectory(filesPath);
                }

                string filePath = filesPath + "/" + DateTime.Now.ToLongDateString()+ ".txt";
                System.IO.FileStream fs = new System.IO.FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Write | FileShare.ReadWrite | FileShare.Read);
                fs.Close();
                System.IO.StreamWriter sw = new StreamWriter(@filePath, true, Encoding.Unicode);
                sw.WriteLine(txt);
                sw.Close();
            }
            catch (Exception ex)
            {
            }
        }

 

4 操作数据库常用方法:

数据库连接:static string connectionString = "Data Source=192.168.100.46;Initial Catalog=ExamDB;User ID=sa;Password=123";//连接数据库语句

查询数据库,返回一个数据集:

public static DataSet Query(string sqlString)
        {
            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    sqlConnection.Open();
                    SqlDataAdapter sqlDataApater = new SqlDataAdapter(sqlString, sqlConnection);
                    sqlDataApater.Fill(ds, "ds");
                }
                catch (SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }

 

public static DataSet Query2(string sqlString)
        {
            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        sqlConnection.Open();                       
                        sqlCommand.CommandText = sqlString;
                        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
                        sqlDataAdapter.Fill(ds);
                    }
                    catch (SqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
        }

 

执行数据库操作,返回影响的行数:

public static int ExecuteSql(string sqlString)
        {
            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                using (SqlCommand sqlCommand = new SqlCommand(sqlString, sqlConnection))
                {
                    try
                    {
                        sqlConnection.Open();
                        int rows = sqlCommand.ExecuteNonQuery();
                        return rows;
                    }
                    catch (SqlException ex)
                    {
                        sqlConnection.Close();
                        throw new Exception(ex.Message);
                    }
                }
            }
        }

 

 

5、生成文件夹

string str = System.IO.Directory.GetCurrentDirectory();
                string firstStr = str.Substring(0, 1);
                string filesPath = firstStr + ":/学习";
                if (!Directory.Exists(filesPath))
                {
                    Directory.CreateDirectory(filesPath);
                }

 

6、获取指定文件内的文件

var imagedir = @"g:\ab/c";
            var imageDirInfo = new DirectoryInfo(imagedir);
            if (!imageDirInfo.Exists)
            {
                imageDirInfo.Create();
                var everyOneSecuity = new DirectorySecurity(imagedir, AccessControlSections.Owner);
                imageDirInfo.SetAccessControl(everyOneSecuity);
            }
            var filesInfo = imageDirInfo.GetFiles();
            Array.Sort(filesInfo, new FIleLastTimeComparer());
            var filesNameStr = string.Empty;
            filesInfo.ToList().ForEach(f => filesNameStr += f.Name + "|");
            string ss = filesNameStr;

 

 获取指定路径path内格式为*.jpg的文件:

方法一:

string[] files = Directory.GetFiles(path, "*.jpg");
            foreach (var dcmFile in files)
            {
            }

 方法二:

DirectoryInfo dInfo = new DirectoryInfo(newPath);
                        foreach (FileInfo dcmFile in dInfo.GetFiles("*.jpg"))
                        {var newDcmFile = dcmFile.Name;

                        }

 

7、执行.exe应用程序:

public static void Dcm2Img(string oriDcm, string descImg)
        {
            Process p = new Process();
            p.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
            p.StartInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + @"dcmtk\dcmj2pnm.exe";
            p.StartInfo.UseShellExecute = false; //是否使用外壳程序
            p.StartInfo.CreateNoWindow = true; //是否在新窗口中启动该进程的值
            p.StartInfo.RedirectStandardInput = true; //重定向输入流
            p.StartInfo.RedirectStandardOutput = true; //重定向输出流
            p.StartInfo.RedirectStandardError = true; //重定向错误流
            //p.StartInfo.Arguments = @"+oj e:\a.dcm 1.jpg";
            p.StartInfo.Arguments = string.Format("+oj {0} {1}", oriDcm, descImg);
            p.Start();
            p.WaitForExit();
            p.Close();
        }

 

//

引用:

.Net那点事儿系列:System.IO之windows文件操作

 

posted @ 2013-11-21 14:09  小项目笔记  阅读(1039)  评论(0编辑  收藏  举报

更多文章请关注公众号:小项目笔记

小项目笔记