c#之文件操作

写文件,这一块我是用了FileStream这个类来实现。

流程如下:

创建一个文件

FileStream m_WriteFs = new FileStream("tttt", FileMode.Create, FileAccess.Write);

写文件(写完之后,文件指针为自动转移到末尾,不需要在seek了)

string strData = "8884848484";
 m_WriteFs.Write(Encoding.Default.GetBytes(strData), 0, Encoding.Default.GetBytes(strData).Length);
m_WriteFs.Seek(0, SeekOrigin.End);

结束:

            m_WriteFs.Flush();
            m_WriteFs.Close();

读取一个文件:

创建一个文件读取类:

FileStream m_ReadFs = new FileStream("tttt", FileMode.Open, FileAccess.Read);

我这边不是从前读取,是从最后读取,所以先定位到最后倒数几位

m_ReadFs.Seek(-11, SeekOrigin.End);

读取4个字节(读完之后,文件指针为自动转移到末尾,不需要在seek了)

m_ReadFs.Read(bCount, 0, 4);

定位到读取完的4个字节后面

m_ReadFs.Seek(-7, SeekOrigin.End);

在读取7个字节

m_ReadFs.Read(bEnd, 0, 7);

关闭文件操作

m_ReadFs.Close();

删除文件或者文件夹

                FileAttributes attr = File.GetAttributes(strPath);
                if (attr == FileAttributes.Directory)
                {
                    Directory.Delete(strPath, true);
                }
                else
                {
                    File.Delete(strPath);
                }

创建一个文件夹

string Time = DateTime.Now.ToString("yyyyMMdd");
string strPath = Path + Time;
if(!Directory.Exists(strPath))
{
    Directory.CreateDirectory(strPath);
}

判断文件夹里面是否存在文件

if (Directory.GetFiles("F:\\20180918\\").Length > 0)
{
    Console.WriteLine("<script>alert('文件夹不为空!');</script>");
}

根据文件全路径获取文件夹

string strFilePath = "F:\\20180918\\4100001203000173_4100001203000173_129_";
int iSub = strFilePath.LastIndexOf("\\");
string strFoldPath = strFilePath.Substring(0, (iSub));

猜你喜欢

转载自blog.csdn.net/g0415shenw/article/details/82624918