개발/Unity

유니티 에셋 - 런타임 파일 브라우저로 파일 저장하기 (Save Files using Runtime File Browser)

피로물든딸기 2022. 7. 2. 17:17
반응형

Unity 전체 링크

 

런타임 파일 브라우저로 파일 업로드하기

 

간단한 파일 브라우저(Simple File Browser)에서 파일을 저장해보자.

 

파일 업로드의 예시 코드에서 파일을 저장하는 코드는 아래와 같이 주석으로 처리되어 있다.

// Show a save file dialog 
// onSuccess event: not registered (which means this dialog is pretty useless)
// onCancel event: not registered
// Save file/folder: file, Allow multiple selection: false
// Initial path: "C:\", Initial filename: "Screenshot.png"
// Title: "Save As", Submit button text: "Save"
// FileBrowser.ShowSaveDialog( null, null, FileBrowser.PickMode.Files, false, "C:\\", "Screenshot.png", "Save As", "Save" );

 

주석을 참고하 FileBrowserTest.cs에 저장 기능을 추가하자.

inputField에 입력된 값을 기본 파일명 "myFile.txt"로 저장하도록 해보자.

경로 + 파일을 선택하면 ShowSaveDialogCoroutine에서 파일을 저장하도록 한다.

    public TMP_InputField inputField;
    
    public void SaveFile()
	{
		string initialPath = "C:\\Users\\[YourPath]";
		string initialFilename = "myFile.txt";
		FileBrowser.ShowSaveDialog(null, null, FileBrowser.PickMode.Files, false, initialPath, initialFilename, "Save As", "Save");

		StartCoroutine(ShowSaveDialogCoroutine(initialPath, initialFilename));
	}

	IEnumerator ShowSaveDialogCoroutine(string initialPath = null, string initialFilename = null)
	{
		yield return FileBrowser.WaitForSaveDialog(FileBrowser.PickMode.FilesAndFolders, false, initialPath, initialFilename, "Save Files and Folders", "Save");

		Debug.Log(FileBrowser.Success);

		if (FileBrowser.Success)
		{
			string path = FileBrowser.Result[0];
			File.WriteAllText(path, inputField.text);
        }
	}

initialPath의 [YourPath]에 원하는 파일 경로를 적으면 된다.

 

FileStream을 이용하려면 아래와 같이 사용하면 된다. (코드가 더 길어진다.)

if (FileBrowser.Success)
{
	string path = FileBrowser.Result[0];
    //File.WriteAllText(path, inputField.text);

    FileStream fileStream
        = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);

    StreamWriter writer = new StreamWriter(fileStream, System.Text.Encoding.Unicode);

    writer.WriteLine(inputField.text);
    writer.Close();
}

 

UI에도 SAVE 버튼과 InputFiled를 추가한다.

 

그리고 InputField에 엔터(Enter)를 입력하면, 줄 바꿈이 되도록 하자.

[Input Field Settings] → [Line Type]Multi Line Newline으로 변경한다.

 

마지막으로 SAVE 버튼의 On Click에 saveFile을 추가한다.

 

이제 InputField에 텍스트를 입력하고 파일을 저장해보자.

원하는 경로에 정상적으로 파일이 생성되는 것을 알 수 있다.

 

FileBrowserTest.cs의 전체 코드는 아래와 같다.

using UnityEngine;
using System.Collections;
using System.IO;
using TMPro;
using SimpleFileBrowser;

public class FileBrowserTest : MonoBehaviour
{
	// Warning: paths returned by FileBrowser dialogs do not contain a trailing '\' character
	// Warning: FileBrowser can only show 1 dialog at a time

	public TextMeshProUGUI fileText;
	public TMP_InputField inputField;

	public void ShowFileBrowser()
	{
		// Set filters (optional)
		// It is sufficient to set the filters just once (instead of each time before showing the file browser dialog), 
		// if all the dialogs will be using the same filters
		FileBrowser
			.SetFilters(true, new FileBrowser
			.Filter("Files", ".jpg", ".png", ".json")
			, new FileBrowser.Filter("Text Files", ".txt", ".pdf"));

		// Set default filter that is selected when the dialog is shown (optional)
		// Returns true if the default filter is set successfully
		// In this case, set Images filter as the default filter
		FileBrowser.SetDefaultFilter(".json");

		// Set excluded file extensions (optional) (by default, .lnk and .tmp extensions are excluded)
		// Note that when you use this function, .lnk and .tmp extensions will no longer be
		// excluded unless you explicitly add them as parameters to the function
		FileBrowser.SetExcludedExtensions(".lnk", ".tmp", ".zip", ".rar", ".exe");

		// Add a new quick link to the browser (optional) (returns true if quick link is added successfully)
		// It is sufficient to add a quick link just once
		// Name: Users
		// Path: C:\Users
		// Icon: default (folder icon)
		FileBrowser.AddQuickLink("Users", "C:\\Users", null);

		// Show a save file dialog 
		// onSuccess event: not registered (which means this dialog is pretty useless)
		// onCancel event: not registered
		// Save file/folder: file, Allow multiple selection: false
		// Initial path: "C:\", Initial filename: "Screenshot.png"
		// Title: "Save As", Submit button text: "Save"
		// FileBrowser.ShowSaveDialog( null, null, FileBrowser.PickMode.Files, false, "C:\\", "Screenshot.png", "Save As", "Save" );

		// Show a select folder dialog 
		// onSuccess event: print the selected folder's path
		// onCancel event: print "Canceled"
		// Load file/folder: folder, Allow multiple selection: false
		// Initial path: default (Documents), Initial filename: empty
		// Title: "Select Folder", Submit button text: "Select"
		// FileBrowser.ShowLoadDialog( ( paths ) => { Debug.Log( "Selected: " + paths[0] ); },
		//						   () => { Debug.Log( "Canceled" ); },
		//						   FileBrowser.PickMode.Folders, false, null, null, "Select Folder", "Select" );

		// Coroutine example
		StartCoroutine(ShowLoadDialogCoroutine());
	}

	public void SaveFile()
	{
		string initialPath = "C:\\Users\\[YourPath]";
		string initialFilename = "myFile.txt";
		FileBrowser.ShowSaveDialog(null, null, FileBrowser.PickMode.Files, false, initialPath, initialFilename, "Save As", "Save");

		StartCoroutine(ShowSaveDialogCoroutine(initialPath, initialFilename));
	}

	IEnumerator ShowSaveDialogCoroutine(string initialPath = null, string initialFilename = null)
	{
		yield return FileBrowser.WaitForSaveDialog(FileBrowser.PickMode.FilesAndFolders, false, initialPath, initialFilename, "Save Files and Folders", "Save");

		Debug.Log(FileBrowser.Success);

		if (FileBrowser.Success)
		{
			string path = FileBrowser.Result[0];
			File.WriteAllText(path, inputField.text);

            //FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);

            //StreamWriter writer = new StreamWriter(fs, System.Text.Encoding.Unicode);

            //writer.WriteLine(inputField.text);
            //writer.Close();
        }
	}

	IEnumerator ShowLoadDialogCoroutine()
	{
		// Show a load file dialog and wait for a response from user
		// Load file/folder: both, Allow multiple selection: true
		// Initial path: default (Documents), Initial filename: empty
		// Title: "Load File", Submit button text: "Load"
		yield return FileBrowser.WaitForLoadDialog(FileBrowser.PickMode.FilesAndFolders, true, null, null, "Load Files and Folders", "Load");

		// Dialog is closed
		// Print whether the user has selected some files/folders or cancelled the operation (FileBrowser.Success)
		Debug.Log(FileBrowser.Success);

		if (FileBrowser.Success)
		{
			// Print paths of the selected files (FileBrowser.Result) (null, if FileBrowser.Success is false)
			for (int i = 0; i < FileBrowser.Result.Length; i++)
				Debug.Log(FileBrowser.Result[i]);

			// Read the bytes of the first file via FileBrowserHelpers
			// Contrary to File.ReadAllBytes, this function works on Android 10+, as well
			byte[] bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result[0]);

			string str = System.Text.Encoding.UTF8.GetString(bytes);
			fileText.text = str;

			// Or, copy the first file to persistentDataPath
			string destinationPath = Path.Combine(Application.persistentDataPath, FileBrowserHelpers.GetFilename(FileBrowser.Result[0]));
			FileBrowserHelpers.CopyFile(FileBrowser.Result[0], destinationPath);
		}
	}
}

 

Unity Plus:

 

Easy 2D, 3D, VR, & AR software for cross-platform development of games and mobile apps. - Unity Store

Have a 2D, 3D, VR, or AR project that needs cross-platform functionality? We can help. Take a look at the easy-to-use Unity Plus real-time dev platform!

store.unity.com

 

Unity Pro:

 

Unity Pro

The complete solutions for professionals to create and operate.

unity.com

 

Unity 프리미엄 학습:

 

Unity Learn

Advance your Unity skills with live sessions and over 750 hours of on-demand learning content designed for creators at every skill level.

unity.com

반응형