zoukankan      html  css  js  c++  java
  • C# .NET Core Linux、Windows统一文件路径解决方法

    我们上传或者下载时需要保存在指定目录,处理windows和linux目录路径问题:

    //方案1  运行时自带
    var path1 = Path.Combine("xxx", "yyy", "zzz");
    //方案2  反斜杠 两个平台都可以用
    var path2 = ("xxx/yyy/zzz");
    //方案3 根据不同环境生成不同文件路径,GetRuntimeDirectory 自己编写
    //判断平台环境,路径可以任意格式"xxx/yyy\zzz" 
    //实际上多个开发协同的时候就是比较混乱,开发环境都没问题,集成的时候报错频繁
    var path3 = GetRuntimeDirectory("xxx/yyy/zzz");

    1、需要引用 System.Runtime.InteropServices

    public static string GetRuntimeDirectory(string path)
    {
        //ForLinux
        if (IsLinuxRunTime())
            return GetLinuxDirectory(path);
        //ForWindows
        if (IsWindowRunTime())
            return GetWindowDirectory(path);
        return path;
    }
    
    //OSPlatform.Windows监测运行环境
    public static bool IsWindowRunTime()
    {  
        return System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
    }
    
    //OSPlatform.Linux运行环境
    public static bool IsLinuxRunTime()
    {
        return System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
    }
    
    public static string GetLinuxDirectory(string path)
    {
        string pathTemp = Path.Combine(path);
        return pathTemp.Replace("\", "/");
    }
    public static string GetWindowDirectory(string path)
    {
        string pathTemp = Path.Combine(path);
        return pathTemp.Replace("/", "\");
    }
  • 相关阅读:
    JDK8 直接定义接口中静态方法
    Spring+Netty+WebSocket实例
    基于Maven,Spring+ActiveMQ实现,贴近实际
    Netty+WebSocket简单实现网页聊天
    ActiveMQ简单入门实例
    WCF 的日志配置
    AutoMapper使用笔记
    博客园现代化建设——AutoMapper
    jqplot formatString 日期格式化列表
    MongoDB实战开发 【零基础学习,附完整Asp.net示例】
  • 原文地址:https://www.cnblogs.com/guozhaoxin/p/14169755.html
Copyright © 2011-2022 走看看