PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 13, 2022

[FIXED] How can I manipulate Windows paths from a Linux app and vice versa in .NET Core?

 September 13, 2022     .net-core, cross-platform, path-manipulation, path-separator     No comments   

Issue

I'm building a data transfer tool that may be deployed to either a Windows or Linux Docker container that must instruct SQL Server to take a database snapshot. Additionally, SQL Server may be on either Windows or Linux and I need to specify where on the server the .ss file will go. I've been using Path.GetFilenameWithoutExtension, Path.Combine, etc but Path operations are done in the context of the OS the app is running in. I need something like WindowsPath.Combine that I can run in Linux when I'm talking to a SQL Server instance on Windows. Right now I do my own string manipulation but I'd prefer to use Path or something purpose built if possible. I know what OS I'm running on and the OS SQL Server is running on and just need an OS agnostic Path.


Solution

I think you'll need to make your own class of static functions to do Windows specific path manipulation. "C:\MyDir\MyFile.ext" can actually be the name of a file on Linux.

You can look at various implementations of .NET Path and you can see that it is just using string manipulation:

https://github.com/microsoft/referencesource/blob/master/mscorlib/system/io/path.cs

I suggest just starting with the methods you need. For example:

public static class PathHelper
{
    public static string GetWindowsFileNameWithoutExtension(string filePath)
    {
        int backslashIndex = filePath.LastIndexOf('\\');
        int dotIndex = filePath.LastIndexOf('.');

        if (backslashIndex >= 0 && dotIndex >= 0 && dotIndex > backslashIndex)
        {
            return filePath.Substring(backslashIndex + 1, dotIndex - backslashIndex - 1);
        }

        if (dotIndex >= 0)
        {
            return filePath.Substring(0, dotIndex);
        }

        return Path.GetFileNameWithoutExtension(filePath);
    }
}


Answered By - Kip Morgan
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing