C#保存和读取文件的方法

保存文件

 string fullPath2=" ";
   System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog();
            dialog.Filter = "文件(*.xls)|*.xls";//设置对话框保存的文件类型
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)//将ok返回默认用户公共对话框
            {
                fullPath2 = dialog.FileName;//获取文件路径和文件名
            }
             if (fullPath2 != "")
            {
                FileInfo fi = new FileInfo(fullPath2);//创建名xls文件
                fi.Directory.Create();
                SaveWaveToFile();//这句是自己创建的保存函数方法,
            }

打开

 private System.Windows.Forms.OpenFileDialog  openFileDialog1 = new System.Windows.Forms.OpenFileDialog() ;
   if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
                string fullPath3= openFileDialog1.FileName;//选择要打开的文件路径
                FileStream fs = new FileStream(fullPath3, FileMode.Open, FileAccess.Read, FileShare.None);
                StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding(936));//
                string str;
                while (sr.Peek() >= 0)
                {
                    str = sr.ReadLine();
                    string[] strSplit = str.Split(',');
                    double[] val = new double[strSplit.GetLength(0)];//strSplit.GetLength(0)表示 str这行的有多少元素,下标从零开始
                    for (int i = 0; i < strSplit.GetLength(0); i++)
                    {
                        if (double.TryParse(strSplit[i], out val[i]))//TryParse将数字的字符串表示形式转换为他的等效双精度浮点数
                        buffer1.Add(val[i]);
                    }
                }
                 sr.Close();
   }

一下部分做参考
关于获取文件的路径的一些其他操作,参考:VB.NET System.IO.Path 文件名、路径、扩展名 处理
string filePath =@“E:/Randy0528/中文目录/JustTest.rar”;

更改路径字符串的扩展名。
System.IO.Path.ChangeExtension(filePath, “txt”);
E:/Randy0528/中文目录/JustTest.txt

返回指定路径字符串的目录信息。
System.IO.Path.GetDirectoryName(filePath);
E:/Randy0528/中文目录

返回指定的路径字符串的扩展名。
System.IO.Path.GetExtension(filePath);
.rar

返回指定路径字符串的文件名和扩展名。
System.IO.Path.GetFileName(filePath);
JustTest.rar

返回不具有扩展名的指定路径字符串的文件名。
System.IO.Path.GetFileNameWithoutExtension(filePath);
JustTest

获取指定路径的根目录信息。
System.IO.Path.GetPathRoot(filePath);
E:/

返回随机文件夹名或文件名。
System.IO.Path.GetRandomFileName();
ct2h5b2h.sed

创建磁盘上唯一命名的零字节的临时文件并返回该文件的完整路径。
System.IO.Path.GetTempFileName();
C:/Documents and Settings/Randy/Local Settings/Temp/tmpAD.tmp

返回当前系统的临时文件夹的路径。
System.IO.Path.GetTempPath();
C:/Documents and Settings/Randy/Local Settings/Temp/

确定路径是否包括文件扩展名。
System.IO.Path.HasExtension(filePath);
True

获取一个值,该值指示指定的路径字符串是包含绝对路径信息还是包含相对路径信息。
System.IO.Path.IsPathRooted(filePath);
True
作者:polloo2012
来源:CSDN
原文:https://blog.csdn.net/polloo2012/article/details/79433072
每个版本的dll都是通过调用相应版本EXCEL内核中的接口,来完成C#中读写EXCEL的所以最好不要用通过COM组件方式读取Excel文件内容

你可能感兴趣的:(C#保存和读取文件的方法)