本日はC#の小ネタ枠です。
Path.Combineで文字列の順序を誤った場合の動作の注意点についてです。
Path.Combine
Path.Combine関数は文字列の配列を結合してパスを生成します。
learn.microsoft.com
string[] paths = {@"d:\archives", "2001", "media", "images"}; string fullPath = Path.Combine(paths); // パス:d:\archives\2001\media\images が生成される
途中にルートパスが含まれた場合の動作
Path.Combineを利用する際は配列の順番に注意が必要です。
配列の途中にルートパスが含まれていた場合、結合操作がリセットされます。
string[] paths = {"2001", "media", @"d:\archives", "images"}; string fullPath = Path.Combine(paths); // パス:d:\archives\images が生成される
途中のルートパスによるリセットが発生してもPath.Combineはエラーを返しません。
意図しないパスが生成された場合は配列の順序を確認してみる必要があります。
サンプルスクリプト
以下のサンプルスクリプトを作成して動作を確認してみます。
・PathCombineTest.cs
using UnityEngine; public class PathCombineTest : MonoBehaviour { [ContextMenu("RunTest")] public void RunTest() { // 複数のディレクトリ名を結合する string[] paths = new string[] { "C:\\", "Alpha", "Beta", "Gamma", "Delta", "Epsilon" }; var fullpath = System.IO.Path.Combine(paths); Debug.Log($"Path.Combine: {fullpath}"); } [ContextMenu("RunTest2")] public void RunTest2() { // 途中にルートパス名を含む複数のディレクトリ名を結合する string[] paths = new string[] { "Alpha", "Beta", "Gamma", "C:\\", "Delta", "Epsilon" }; var fullpath = System.IO.Path.Combine(paths); Debug.Log($"Path.Combine: {fullpath}"); } }
以下の通り順番を誤って途中にルートパス名を含む配列の場合、その前の文字列が消去されて結合されています。
