C# - Easiest way to parse filename with spaces eg. “C:\Test\File with spaces.txt”

前端 未结 6 2222
孤独总比滥情好
孤独总比滥情好 2021-01-04 23:30

I am trying to pass a full file path to FFMPEG.

C:\\TestFolder\\Input\\Friends - Season 6 - Gag Reel.avi

and it\'s obviously not liking th

6条回答
  •  萌比男神i
    2021-01-04 23:57

    I agree with the above post. To make it easier, here's the code you need to use. In My Humble Opinion, the only good file name is a space-free file name.

    Therefor in c# code I have this:

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern uint GetShortPathName(
       [MarshalAs(UnmanagedType.LPTStr)]
        string lpszLongPath,
       [MarshalAs(UnmanagedType.LPTStr)]
        StringBuilder lpszShortPath,
       uint cchBuffer);
    
    public static StringBuilder shortNameBuffer = new StringBuilder(256);
    public static string ToShortPathName(string longName)
    {
      uint result = GetShortPathName(longName, shortNameBuffer, 256);
      return shortNameBuffer.ToString();
    }
    

    That adds a method to your class that can be used like this:

    String goodFileName = ToShortPathName(evilFileName);

    NOTE: I'm using this in a UI so I don't mind being non-thread safe and reusing the StringBuider. If you're in a multi-threaded environment, make sure to pull the StringBuilder allocation inside your method.

提交回复
热议问题