C#的技巧代码

一、基本知识

1.文件夹和文件路径、名字的处理

(1)获得文件的绝对路径

file.FullName是获得file文件的绝对路径

(2)获得文件的父级目录、不带扩展名的文件名、上层目录

场景
现在有一个文件路径
E:\BTSData\2019-11\admin_20180918_1_1_2
需要获取最后的文件名admin_20180918_1_1_2
需要获取文件的上层目录2019-11
需要获取最后文件名中的最后的1和2

实现
首先获取完整的文件路径,不带扩展名的

E:\BTSData\2019-11\admin_20180918_1_1_2

赋值为result变量

然后要获取其父级目录

result = System.IO.Directory.GetParent(result).ToString();

此时result为E:\BTSData\2019-11

然后再进行截取

result = result.Substring(result.LastIndexOf('\\')+1);

此时result为2019-11,得到上层目录

然后通过完整路径获取不带扩展名的文件名

string fileName = System.IO.Path.GetFileNameWithoutExtension(result);

此时文件名fileName为admin_20180918_1_1_2

(3)获取文件的后缀名、文件名

  string directory = Path.GetDirectoryName(localFilePath);  
  //文件所在路径      C:\Users\yhood\Desktop
  string filename = Path.GetFileNameWithoutExtension(localFilePath);  
  //文件名    林业局考勤06
  string extension = Path.GetExtension(localFilePath);    
  //文件后缀 带点(.)     .xlsx

3.string的操作

(1)对string字符串按照指定字符进行分段

admin_20180918_1_1_2按照’_'进行分段

string[] titles = result.Split('_');    //分段
titles[titles.Length - 2];   //获取倒数第二个片段

(2)获得string字符串的左边n个字符或者右边n个字符、去掉某位置的字符

1、取字符串的前i个字符
(1)string str1=str.Substring(0,i);
(2)string str1=str.Remove(i,str.Length-i);

2、去掉字符串的前i个字符
string str1=str.Remove(0,i);
string str1=str.SubString(i);

3、从右边开始取i个字符:
string str1=str.SubString(str.Length-i);
string str1=str.Remove(0,str.Length-i);

4、从右边开始去掉i个字符:
string str1=str.Substring(0,str.Length-i);
string str1=str.Remove(str.Length-i,i);

5、

6 、如果字符串中有"abc"则替换成"ABC"
str=str.Replace(“abc”,“ABC”);

7、c#截取字符串最后一个字符的问题!!!!!!!!!!!!!!!!!!!!!
str1.Substring(str1.LastIndexOf(",")+1);

8、C# 截取字符串最后一个字符

k = k.Substring(k.Length-1, 1);

(3)C# String 前面不足位数补零的方法

一:在 C# 中可以对字符串使用 PadLeft (左边补)和 PadRight (右边补)进行轻松地补位。

PadLeft(int totalWidth, char paddingChar) //在字符串左边用 paddingChar 补足 totalWidth 长度
PadLeft(int totalWidth, char paddingChar) //在字符串右边用 paddingChar 补足 totalWidth 长度
例如:
1、string aa = “wu”;
string bb = aa.PadLeft(6);//右对齐此实例中的字符,在左边用空格填充以达到指定的总长度.
string cc = aa.PadLeft(6, ‘0’);//右对齐此实例中的字符,在左边用指定的 Unicode 字符填充以达到指定的总长度。
2、Pznm =(snode.InnerText).ToString().PadLeft(10,‘0’);
字符串固定为10位,不足10位左边补零。

二:String.Format("{0:D5}",16);
or
int i=16;
i.ToString(“D5”);
Result: 00016

5代表位数

int i=10;
方法1:Console.WriteLine(i.ToString(“D5”));
方法2:Console.WriteLine(i.ToString().PadLeft(5,‘0’));//推荐
方法3:Console.WriteLine(i.ToString(“00000”));

在 C# 中可以对字符串使用 PadLeft 和 PadRight 进行轻松地补位。

PadLeft(int totalWidth, char paddingChar) //在字符串左边用 paddingChar 补足 totalWidth 长度
PadRight(int totalWidth, char paddingChar) //在字符串右边用 paddingChar 补足 totalWidth 长度
示例:
h = h.PadLeft(2, ‘0’);
注意第二个参数为 char 类型,所以用单引号,也可以用 Convert.ToChar(string value) 把字符串转换成 char 类型。如果字符串长度大于 1,则使用 str.ToCharArray()[index]

(4)定义string数组

string[] excel_record =new string [25] ; //正确,指定大小
string[] excel_record =new string [25] {};//报错
string[] excel_record ={} ;//不报错,但是后面使用excel——record[0]输入数据的时候报错,因为这里没有指定string数组的大小

二、功能

1.文件夹的处理

(1)获得当前文件夹下的所有视频的路径

调用videoAddress函数,输入文件夹路径即可得到文件夹下的所有视频的路径,file.FullName是获得视频的绝对路径,file是视频名

      // 获取一个文件下的每个视频地址
      /* 
       * DirectoryInfo 位于System.IO
       * @param path : 视频目录的地址  
       * example:
       *        string path = @"E:\File";
       * @return List : 存储视频地址的容器
      */
      public List<string> videoAddress(string path) {
          List<string> list = new List<string>();
          DirectoryInfo folder = new DirectoryInfo(path);
          foreach (FileInfo file in folder.GetFiles("*.mp4")) {
              list.Add(file.FullName);
          }
          // Console.WriteLine(list.Count());
          return list;
      }
      // 打印查看 
      public void printVideoAddress(List<string> list) {
          foreach (var file in list) {
              Console.WriteLine(file);
          }
      }

(2)创建文件夹

https://www.cnblogs.com/winformasp/articles/10893888.html
这个链接非常详细

通过Path类的Combine方法可以合并路径。

string activeDir = @"C:\myDir";
string newPath = System.IO.Path.Combine(activeDir, "mySubDirOne");
//创建存储文件夹
string file_video_every = file_video + "/" + fileName ;
//检查是否存在文件夹
if (false == System.IO.Directory.Exists(file_video_every))
{
    //创建pic文件夹
    System.IO.Directory.CreateDirectory(file_video_every);
}

(3)获取文件夹下的所有文件夹的名字

DirectoryInfo folder = new DirectoryInfo(path);
foreach (FileSystemInfo file_video in folder.GetFileSystemInfos())
{
//处理txt文件的特殊情况
    textBox3.Text += "file_video= " + file_video + "\r\n";
    string extension = Path.GetExtension(file_video.FullName.ToString());
}

(4)文件夹下的文件移动

 //将视频复制到创建的文件夹内
 string sourceFile = Video_path;
 string destFile = file_video_every + "/" + fileName +".mp4";
 System.IO.File.Move(sourceFile, destFile);

(5)文件夹下的文件复制


System.IO.File.Copy(sourceFile, destFile, true);

2.创建txt文件,写入数据

        //注册
        public string registered(string username,string password)
        {            //判断是否已经有了这个文件
            if (!System.IO.File.Exists("c:\\users\\administrator\\desktop\\webapplication1\\webapplication1\\testtxt.txt"))
            {
               //没有则创建这个文件
                FileStream fs1 = new FileStream("c:\\users\\administrator\\desktop\\webapplication1\\webapplication1\\testtxt.txt", FileMode.Create, FileAccess.Write);//创建写入文件                //设置文件属性为隐藏
                System.IO.File.SetAttributes(@"c:\\users\\administrator\\desktop\\webapplication1\\webapplication1\\testtxt.txt",  FileAttributes.Hidden);    
                StreamWriter sw = new StreamWriter(fs1);
                sw.WriteLine(username.Trim() + "+" + password.Trim());//开始写入值
                sw.Close();
                fs1.Close();
                return "注册成功";
            }
            else
            {
                FileStream fs = new FileStream("c:\\users\\administrator\\desktop\\webapplication1\\webapplication1\\testtxt.txt", FileMode.Open, FileAccess.Write);
                System.IO.File.SetAttributes(@"c:\\users\\administrator\\desktop\\webapplication1\\webapplication1\\testtxt.txt", FileAttributes.Hidden);
                StreamWriter sr = new StreamWriter(fs);
                sr.WriteLine(username.Trim() + "+" + password.Trim());//开始写入值
                sr.Close();
                fs.Close();
                return "注册成功";
            }
 
        }

https://blog.csdn.net/weixin_34138377/article/details/94028486
参考的这个链接

3.创建Excel文件,并写入数据

【自学笔记小白专用 从菜鸟到高手】C#_创建Excel文件实例操作
这个链接写的比较全面
C# 创建Excel并写入内容
这个链接是下面的代码,比较简洁

基本的用法
第一步:首先添加Microsoft.Office.Interop.Excel组件
在这里插入图片描述

在这里插入图片描述

第二部:引用命名空间(代码中)

 using Excel = Microsoft.Office.Interop.Excel;

第三步:创建excel

  1. 下面的代码中定义了创建excel的函数,FileName是路径名+想要创建excel的名字(para.xlsx或者不加xlas,直接使用para,例如:D:\project\para)
  2. worksheet.Name = “Work”;没有弄明白用处
  3. worksheet.Cells[1, 1] = “FileName”;在创建一个新的表的时候通常会将第一行设置为属性名,此行代码就是将第一行第一列的内容设置为"FileName"
/// <summary>
        /// If the supplied excel File does not exist then Create it
        /// </summary>
        /// <param name="FileName"></param>
        private void CreateExcelFile(string FileName)
        {
            //create
            object Nothing = System.Reflection.Missing.Value;
            var app = new Excel.Application();
            app.Visible = false;
            Excel.Workbook workBook = app.Workbooks.Add(Nothing);
            Excel.Worksheet worksheet = (Excel.Worksheet)workBook.Sheets[1];
            worksheet.Name = "Work";
            //headline
            worksheet.Cells[1, 1] = "FileName";
            worksheet.Cells[1, 2] = "FindString";
            worksheet.Cells[1, 3] = "ReplaceString";

            worksheet.SaveAs(FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
            workBook.Close(false, Type.Missing, Type.Missing);
            app.Quit();
        }

第四步:添加数据

  1. excelName参数是xlsx的路径
  2. 后面的三个参数是想要输入到xlsx文件夹中的三列的数据,当然我们也可以重新定义函数名为private void WriteToExcel(string excelName, string[] para) 使用string数组存储数据,这样看起来比较清楚
  3. mysheet.Cells[maxrow, 1] = filename;这行代码是写入数据的代码,maxrow行,1列输入数据filename。这里maxrow是没有写入数据的第一行(int maxrow = mysheet.UsedRange.Rows.Count + 1;)
/// <summary>
        /// open an excel file,then write the content to file
        /// </summary>
        /// <param name="FileName">file name</param>
        /// <param name="findString">first cloumn</param>
        /// <param name="replaceString">second cloumn</param>
        private void WriteToExcel(string excelName,string filename,string findString,string replaceString)
        {
            //open
            object Nothing = System.Reflection.Missing.Value;
            var app = new Excel.Application();
            app.Visible = false;
            Excel.Workbook mybook = app.Workbooks.Open(excelName, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing);
            Excel.Worksheet mysheet = (Excel.Worksheet)mybook.Worksheets[1];
            mysheet.Activate();     
            //get activate sheet max row count
            int maxrow = mysheet.UsedRange.Rows.Count + 1;
            mysheet.Cells[maxrow, 1] = filename;
            mysheet.Cells[maxrow, 2] = findString;
            mysheet.Cells[maxrow, 3] = replaceString;
            mybook.Save();
            mybook.Close(false, Type.Missing, Type.Missing);
            mybook = null;
            //quit excel app
            app.Quit();
        }
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值