Unity Load text from resources - c#

I'm able to change the text of a UILabel (named about) with the following:
using UnityEngine;
using System.Collections;
public class about : MonoBehaviour
{
void Start ()
{
UILabel lbl = GetComponent<UILabel>();
lbl.text = "Hello World!";
}
}
However things go awry when I want to load the label text from a text file in resources (Assets/Resources/about.txt)
lbl.text = Resources.Load(Application.dataPath + "/Resources/about") as String
So I'm not sure where I'm going wrong, and yes I have looked here.

Simply use this:
TextAsset mytxtData=(TextAsset)Resources.Load("MyText");
string txt=mytxtData.text;
and you can use the txt string to fulfill your requirement, just make sure that MyText.txt is in Assets > Resources

Have you tried one of these:
TextAsset mydata = Resources.Load("MyTexts/text", typeof(TextAsset));
TextAsset mydata = Resources.Load("MyTexts/text") as TextAsset;
Here, "MyTexts/text" is the asset name, which will actual refere the file text.txt.
The asset should be placed inside the Assets folder this way:
Assets/MyTexts/text
On the filesystem you will have:
.../Assets/MyTexts/text.txt
Don't use Application.dataPath or anything like that, you're loading a statically linked asset from the binary asset file.
The loaded mydata is binary. Use Encoding.ASCII.GetString(mydata.bytes) to get an actual string out of it.

var loaded_text_file = Resources.Load("mytexts/myfiletextname") as TextAsset;
string txt = loaded_text_file.text;

I was having a hard time loading 'TextAsset' files, until I discovered that only certain file extensions can be used. In my case I was trying to use '.yml', but unity will only read '.yaml'.
Full details here: https://docs.unity3d.com/Manual/class-TextAsset.html

I searched for alot of methods online and implemented them, but none of them worked. So I went to Unity docs. Here is a link hope it helps.
Unity Read Resource Read it carefully.
Edit:
here is a simple implementation:
Create Resources folder in Assets.
Place your text file in that folder(Resources).
code:
var textFile = Resources.Load<TextAsset>("file name only not path and no file extension(.txt)");
//store it in any List line by line(optional)
List<String> words = new List<string>(textFile.text.Split('\n'));

Related

Why is the absolute path used to read text files in C #, and the path will change

I use unity3d and vs2019 to read a text file (txt) as follows:
public class MeshTest01 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
string filePath = #"‪‪‪D:\Desktop\Unity\Mesh\77.txt";
string[] lines = File.ReadAllLines(filePath);
foreach (var item in lines)
{
Debug.Log(item);
}
//List<string> planesStr = TxtOperation.GetFaces2str(linesStr);
//Debug.Log(TxtOperation.GetFaceIndex(planesStr[0]));
}
}
The error information is as follows:
DirectoryNotFoundException: Could not find a part of the path "E:\project\GitHub\RobotSimulation\***D:\Desktop\Unity\Mesh\77.txt".
Why does the previous part of the file path appear
Honestly, I can't explain why this happens.
Usually yes, this would be one way of how to read an external file.
My guess would be that since your file is placed on a different drive the project might be sandboxed and therefore interprets the path as a relative one. Never tried to load files from different drives to be honest.
However, in general I would keep the files together with the project they belong to and place them
either in the Application.streamingAssetsPath in the editor in the folder Assets/StreamingAssets for files that shall be
read/write able for the editor
but readonly later in a build
or the Application.persistentDataPath for builds if you want to
write to them via code
or let the user change the content
externally afterwards
Then you would get your path using
var path = Path.Combine(Application.streamingAssetsPath, "SomeFolder", "77.txt");
or accordingly
var path = Path.Combine(Application.persistentDataPath, "SomeFolder", "77.txt");
For the streaming assets there are some special cases (e.g. on Android) where you need to read the file using UnityWebRequest.Get since it gets compressed.
Alternatively if it is an option for you you could also directly drag it into the Assets (or any folder below except special ones like StreamingAssets, Resources etc) and then directly drag it into a field via the Inspector using it as a (read-only) TextAsset
[SerializeField] private TextAsset meshFile;
and later access it's content via
var lines = meshFile.text.Split('/n');
Also I general: You should make a huge circle around the Resources!
Unity themselves strongly recommend to not use it! This and the reasons can be found in the Best practices.

TagLib-Sharp - Retagging files

im about to create a small tool, which recreates all tags on my mp3 files.
Because they are in a mess, i want to remove all tags and recreate them with the correct values.
Doing so ive encountered the problem that im not able to set the tag values.
But the problem is, that im not able to set the tags. I have the following code:
File tagLibFile = File.Create(filePath);
tagLibFile.RemoveTags(TagLib.TagTypes.AllTags);
tagLibFile.Tag.Album = album;
tagLibFile.Tag.AlbumArtists = artists.ToArray();
tagLibFile.Tag.Track = track;
tagLibFile.Tag.Title = title;
tagLibFile.Tag.TitleSort = titleSort;
...
tagLibFile.Save();
The file is read out correctly. Then the tags are removed.
But after that setting the Tag does not work. The strings inside the tag are still null.
I havent seen a method like "tagLibFile.SetTag(Tag t)". The Tag is only available as a getter, but not a setter.
After that ive added some Frames, but that doesent have the effect of setting the tags. Maybe im using it the wrong way?
Hope you can help me out of this!
Kind regards,
SyLuS
I'm guessing that after removing tags, TagLib# (or TagLib, for that matter) does not create a new tag to hold information. However, when opening a file, it possibly does some checking and if the file doesn't have one, it creates a new tag.
Hence, as a workaround, you could save the file once after removing the tags, and then proceed to add new tag information.
File tagLibFile = File.Create(filePath);
tagLibFile.RemoveTags(TagLib.TagTypes.AllTags);
// Save the file once, so that Taglib Sharp takes care of creating any necessary tags when opening the file next time and dispose the file reference:
tagLibFile.Save();
tagLibFile.Dispose();
You can then proceed to editing the tags as you're already doing after opening the file again:
tagLibFile = File.Create(filePath);
tagLibFile.Tag.Album = album;
tagLibFile.Tag.AlbumArtists = artists.ToArray();
tagLibFile.Tag.Track = track;
tagLibFile.Tag.Title = title;
tagLibFile.Tag.TitleSort = titleSort;
// ...
Remember to save the file again, after you're done editing tags:
tagLibFile.Save();
I hope this helps. If you have any further questions, or the above code doesn't work still, feel free to comment. :)

Embed File in a Executable

I'm trying to build a simple program and I want to find a way to embed a file (or multiple files) in the executable.
The program is very simple. I will be building a form using C# in visual studio. On the form, there will be couple questions and a submit button.
Once the user has answer all the questions and hit the submit button, if all answers are correct, I want to give the user the file as a prize. (The file can be image, video, or a zip file that contains multiple other files)
The way I want to give the user the file is very flexible. It can just be creating this file in the same directory as the executable, or given the download option for the user to save it somewhere else.
Below is the pseudo code
private void submit_Click(object sender, EventArgs e)
{
//functions to check all answers
if(all answers are correct)
{
label.Text = "Congrats! You answered all questions correctly";
//create the file that was embeded into the same directory as the executable
//let's call the file 'prize.img'
Process.Start("prize.img");
}
else
label.Text = "Some answers were not correct";
}
The logic is pretty simple and straight forward. The problem is, how can I embed "prize.img" into the executable? I will be giving this program (.exe) to a friend so he will not have any source and I can't guarantee the path.
You want to do embed the file as a resource.
Right-click the project file, select Properties.
In the window that opens, go to the Resources tab, and if it has just a blue link in the middle of the tab-page, click it, to create a new resource.
In your code you can type in Resources.TheNameYouGaveTheFileHere and you can access its contents. Note that the first time you use the Resources class in a class, you need to add a using directive (hit Ctrl+. after typing Resources to get the menu to get VS to do it for you).
Do you need help with the saving of the file also?
Edit:
You could do something like this:
var resource = Properties.Resources.yourResource;
FileStream fileStream = new FileStream("filename.exe", FileMode.CreateNew);
for (int i = 0; i < resource.Length; i++)
fileStream.WriteByte((byte)resource[i]);
fileStream.Close();
Does it help you?
EDIT:
As I can see you are getting a stream, here is an update to make it work:
var resource = Properties.Resources.yourResource;
FileStream fileStream = new FileStream("filename.exe", FileMode.CreateNew);
resource.CopyTo(fileStream);
fileStream.Close();
Does it work now?
Can't you add the image file as a resource in your solution? And then you can reference that resource in your code?
See if this may be what you're looking for:
Embedding Image Resource in Project
The link provided offers step-by-step how to accomplish this:
After adding the image as a resource, the instructions show how to access your image resource and use it in a program. Just click the link above and follow the instructions.
I followed the instructions above and wrote my program like this:
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var myAssembly = Assembly.GetExecutingAssembly();
var myStream = myAssembly.GetManifestResourceStream("WindowsFormsApplication6.Desert.jpg");
var image = new Bitmap(myStream);
pictureBox1.Image = image;
}
}
}
My output looks like this:
The image on the form came from the image that I embedded as a resource. Very easy to do.
Add the file into project then set its Build Action as Embeded resource.
From your code you can do something like this:
var _assembly = Assembly.GetExecutingAssembly();
var _stream = _assembly.GetManifestResourceStream("namespace.fileneme");

Reading/Writing metadata of audio/video files

I need some help in reading/writing meta data inforamation of audio/vido file. I have searched alot but not find anything thing helpful. Taglib sharp is an open source library that provide help in reading/writing metadata. Using tag lib i'm able to edit some of values but not all like.
TagLib.File videoFile = TagLib.File.Create("test.mp4");
videoFile.Tag.Title = "Test";
videoFile.Tag.Comment = "Nothing";
but i'm unable to edit following properties like Author url, producers etc. How i edit these properties ??
I've never done this for video files before but I have for mp3 files. You can get access to those frames like this:
TagLib.File file = TagLib.File.Create(mp3FileName);
file.Tag.Title = "some title"; // you've got this
TagLib.Id3v2.Tag tag = (TagLib.Id3v2.Tag)file.GetTag(TagTypes.Id3v2);
tag.SetTextFrame("WOAR", "some url"); // WOAR = Official artist/performer webpage
file.Save();
You can find a list of the text frame identifiers at Wikipedia:
ID3v2 Frame Specification (Version 2.3)
I don't know if video files give you the same range of frames that ID3 does, though notice that Wikipedia also says (Implementation in non-mp3s and alternatives)
MP4 also allows the embedding of an ID3 tag, and this is widely supported.
So I would guess this also works for mp4 files like you're trying.
You will need to use AppleTag. This will work. For mp4 file you have to write value into dashbox. Like this:
TagLib.File videoFile = TagLib.File.Create("test.mp4");
TagLib.Mpeg4.AppleTag customTag = (TagLib.Mpeg4.AppleTag)f.GetTag(TagLib.TagTypes.Apple);
customTag.SetDashBox("Producer","Producer1", "value");
f.Save();
f.Dispose();
And you can get the value like this:
var tokenValue = customTag.GetDashBox("Producer", "Producer1");

How to give path to an text file in Solution using XDocument?

I want to load a xml document Swedish.xml which exists in my solution. How can i give path for that file in Xamarin.android
I am using following code:
var text = File.ReadAllText("Languages/Swedish.txt");
Console.WriteLine("text: "+text);
But i am getting Exception message:
Could not find a part of the path "//Languages/swedish.txt".
I even tried following lines:
var text = File.ReadAllText("./Languages/Swedish.txt");
var text = File.ReadAllText("./MyProject/Languages/Swedish.txt");
var text = File.ReadAllText("MyProject/Languages/Swedish.txt");
But none of them worked. Same exception message is appearing. Build Action is also set as Content. Whats wrong with the path? Thanks in advance.
Just try with this
string startupPath = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.FullName, "Languages", "Swedish.txt");
var text = File.ReadAllText(startupPath);
Try...
Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments)+"/Languages/Swedish.txt"
If you mark a file as Content Type, it will be included in the app bundle with the path that you are using within your project file. You can inspect the IPA file (it's just a renamed zip) that is created to verify that this is happening.
var text = File.ReadAllText("Languages/Swedish.txt");
should work. The file path is relative to the root of your application. You need to be sure that you are using the exact same casing in your code that the actual file uses. In the simulator the casing will not matter, but on the device the file system is case sensitive, and mismatched casing will break the app.
I've looked into this before and never found any solution to access files in this way. All roads seem to indicate building them as "content" is a dead end. You can however place them in your "Assets" folder and use them this way. To do so switch the "Content" to "AndroidAsset".
After you have done this you can now access the file within your app by calling it via
var filename = "Sweedish.txt";
string data;
using
(var sr = new StreamReader(Context.Assets.Open(code)))
data = sr.ReadToEnd();
....

Categories