本日はC#の小ネタ枠です。
相対ファイルパスから絶対パスのURIを取得する方法を記事にします。
相対ファイルパスから絶対パスのURIを取得する
URIクラスは生成時にUriKindを指定して相対パスまたは絶対パスのURIを生成できます。
learn.microsoft.com
相対パスで生成したURIからは絶対パスを参照できません。
絶対パスのURIが必要な場合は以下のようにFileInfoを経由して絶対パスを取得した上でURIを生成します。
string filePath = "steamingAssets/test.txt"; System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); Uri absoluteUri = new Uri(fileInfo.FullName);
サンプルスクリプト
相対パスから絶対パスのURIを取得する以下のサンプルスクリプトを作成しました。
ShowRelativeFileURIでは絶対パスの参照に失敗しますが、ShowAbsoluteFileURIは絶対パスのURIが生成できます。
・URITest.cs
using System; using UnityEngine; public class URITest : MonoBehaviour { [ContextMenu("Show Relative File URI")] public void ShowRelativeFileURI() { Debug.Log("Show Relative File URI"); string filePath = "steamingAssets/test.txt"; Debug.Log("File Path: " + filePath); // 相対パスでファイルのURIを取得する Uri relativeUri = new Uri(filePath, UriKind.Relative); // 相対パスのURIは絶対パスのURIを参照できない Debug.Log("Relative File URI: " + relativeUri.AbsoluteUri); } [ContextMenu("Show Absolute File URI")] public void ShowAbsoluteFileURI() { Debug.Log("Show Absolute File URI"); string filePath = "steamingAssets/test.txt"; Debug.Log("Root Path: " + Application.dataPath); Debug.Log("File Path: " + filePath); // FileInfoを使って絶対パスのURIを取得する System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); Uri absoluteUri = new Uri(fileInfo.FullName); // 絶対パスのURIを表示する Debug.Log("Absolute File URI: " + absoluteUri.AbsoluteUri); } }