C# I/O

获取运行时的动态目录

private static string GetDataDir_Data()
{
      var parent = Directory.GetParent(Directory.GetCurrentDirectory()).Parent;
      string startDirectory = null;
      if (parent != null)
      {
           var directoryInfo = parent.Parent;
           if (directoryInfo != null)
           {
                startDirectory = directoryInfo.FullName;
           }
       }
       else
       {
            startDirectory = parent.FullName;
       }
       return Path.Combine(startDirectory, "Data\\");
}

//参考之Aspose.Words-for-.NET-master

//其他

string d2 = AppDomain.CurrentDomain.BaseDirectory;
var touristRouteJsonData = File.ReadAllText(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"/Database/touristRoutesMockData.json");

net core 项目中

常用工具方法 

文件扩展名

string fileExtension = Path.GetExtension(fileName)//全路径,返回带点
Directory.CreateDirectory(exportPath)

 I/O操作之文件,目录删除

判断目录是否存在

public void CleanTempPath(TCPRptParamInfo param)
{
    string TempPath = ConfigHelper.ReadConfig("TempPath");
    string returnStr = TempPath + "\\" + param.SubTempDirectory + "\\";

    if (Directory.Exists(returnStr))
    {
        FileInfo[] fi = new DirectoryInfo(returnStr).GetFiles();
        int fileLenght =  fi.Length;
        for (int i = 0; i < fileLenght;  i++)
        {
            fi[i].Delete();
        }
        //Directory.Delete(returnStr); //删目录,非空目录不能直接删除
    }
}
if (Directory.Exists(returnStr))
{
    Directory.Delete(returnStr,true);//直接删除非空目录
}

 读文本方式之一

string dataDir = AppDomain.CurrentDomain.BaseDirectory; //Get Current Directory

StreamReader srPerson = File.OpenText(FaleName1);//文本文件完整路径
StreamReader strData = File.OpenText(dataDir + "data.txt");
while (!strData.EndOfStream)
{
    string textLine = srPerson.ReadLine();
    //TODO
}

 读文本方式之二

using System.IO;

string dataPath = GetMaterialPath(param, DocType.LeaderAttribute) + "data.txt";
string configstr = System.IO.File.ReadAllText(dataPath, Encoding.Default); //核心方法:读文本方式之一
Dictionary<string, string> allConfig = ConfigHelper.ParseConfigString(configstr);

public static class ConfigHelper
{
    public static string ReadConfig(string key)
    {
        return System.Configuration.ConfigurationManager.AppSettings[key];
    }

    public static Dictionary<string, string> ParseConfigString(string config)
    {
        Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
        string[] array = config.Split(new char[]
        {
            ''//行结束标记
        });
        string[] array2 = array;
        for (int i = 0; i < array2.Length; i++)
        {
            string text = array2[i];
            string[] array3 = text.Split(new char[]
            {
                ':'
            });
            if (array3.Length == 2)
            {
                dictionary.Add(array3[0].Trim(), array3[1].Trim());
            }
            else
            {
                dictionary.Add(text.Trim(), null);
            }
        }
        return dictionary;
    }
}

 写文件(追加)参考

FileInfo fi = new FileInfo(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"SBILog.txt");//创建一个文件信息
if (fi.Exists && fi.Length > 1024 * 1024)
{//先判断是否存在改名称的文件,并且判断文件的大小
    fi.Delete();
}
FileStream fs = new FileStream(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"SBILog.txt", FileMode.OpenOrCreate, FileAccess.Write);//创建一个文件流
StreamWriter m_streamWriter = new StreamWriter(fs);//创建一个文件输入流
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);//字符追加的位置
m_streamWriter.WriteLine("Msg:" + DateTime.Now.ToString() + " -- " + System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\n");//向文件中写入字符串
m_streamWriter.Flush();//清除此流的缓冲区,使得所有缓冲的数据都写入到文件中。
m_streamWriter.Close();//关闭输入流
fs.Close();//关闭文件流
public string Path = AppDomain.CurrentDomain.BaseDirectory;
public string DataSource = "\\Txt\\yun_data.txt";
public string ToMatch = "\\Txt\\lost.txt";

public List<string> DataSourceList = new List<string>();
public void Run()
{
    FileStream fs = new FileStream(Path + @"\\Txt\\SBILog.txt", FileMode.OpenOrCreate, FileAccess.Write);//创建一个文件流
    StreamWriter m_streamWriter = new StreamWriter(fs);//创建一个文件输入流

    StreamReader strData = File.OpenText(Path + DataSource);
    while (!strData.EndOfStream)
    {
        string text = strData.ReadLine().Trim();
        DataSourceList.Add(text);
    }
    strData.Close();

    //待查找到文件名
    strData = File.OpenText(Path + ToMatch);
    while (!strData.EndOfStream)
    {
        string text = strData.ReadLine().Trim();
        Match TitleMatch = Regex.Match(text, @"\[([^\[\]]*)\]"); //抓取由方括号界定的字符
        string titleKey = TitleMatch.Groups[1].Value;
        foreach (string item in DataSourceList) {
            if (item.IndexOf(titleKey) > 0)
            {
                string log = text + "=>" + item;
                m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);//字符追加的位置
                m_streamWriter.WriteLine(log + "\n");//向文件中写入字符串
            }
        }
    }
    strData.Close();
    //
    m_streamWriter.Flush();//清除此流的缓冲区,使得所有缓冲的数据都写入到文件中。
    m_streamWriter.Close();//关闭输入流
    fs.Close();//关闭文件流
}

 

posted @ 2017-01-05 13:59  轴轴  阅读(308)  评论(0编辑  收藏  举报