I am (after some strangeness with my resources file) able to play a .wav file in my project:
SoundPlayer player = new SoundPlayer();
player.Stream = Sounds.L1;
Player.Play();
This works fine but what I want to do is be able to concatenate a string together and then call the file. The .wav filename would be of the form "L" + int, with int being anywhere between 1 - 99 i.e. L1, L2...L99. All the different sound files are in a resx file title Sounds.
How would I be able to call them?
I am trying to use the ResXResourceSet resxSet = new ResXResourceSet("btc.Sounds") ResXResourceSet to load the resources file and then use the .getobject() as suggested. However, how do you specify the location of the embedded resource file? If I use a path as above I get an error as it is looking in my bin/debug folder, which is where the .exe is placed. If I explicityly specify the path I get an access error and one thing I am really curious about is the fact that the 'Sounds.resx' file is an embedded resource so it should 'know' where it is and shouldn't need any path... I have tried pretty much every permutation including using Assembly.GetExecutingAssembly().GetManifestResourceStream("btc_I_Cap.Sounds"), #"....\Sounds" #"....\Resources", #"btc.Sounds" "Sounds.resx" and so on and so far nothing. Can someone please put me out of my misery so that I can go 'oh yeah, that was obvious why didn't I think of that!'
Happy halloween.
Thanks.
Use a ResXResrouceSet to call the sound file Something like this:
using (ResXResourceSet resxSet = new ResXResourceSet(resxFile))
{
for (int i = 1; i <= 99; i ++)
{
SoundPlayer simpleSound = (SoundPlayer)resxSet.GetObject("L" + i.ToString());
simpleSound.Play();
}
}
Related
I have been using external txt files to save the score and the player name (I only save one score and one name in two different files)
When there is a new highscore it saves over the old one. I had it all working perfectly until I published the project, now it cant locate the file.
I embedded the txt file but I cant write to it.
I am using the following code.
using (StreamWriter write = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "highscore.txt")) // read the high score text file
{
write.WriteLine(player.score); // saves the new high score
write.Close(); // closes the file
}
using (StreamWriter write = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "nickname.txt")) // reads the high score text file
{
write.WriteLine(player.nickname); // save new highscore name
write.Close(); // close file
}
When I run the games from a USB or a CD they wont read -
So my question is - how to I place the txt files into a directory my game can see/find?
When you are running your program from the CD, your application's path is on that CD, so the code:
AppDomain.CurrentDomain.BaseDirectory + "highscore.txt"
points to a readonly CD path.
in order to be able to save the file properly, you can:
ask user to enter a path to which he/she wants the data to be saved
use one of the available directories (look in the Environment class),
for instance using the:
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Please also note that it is better to use Path.Combine() to concat the paths rather than '+' sign.
I am currently working in Unity3D and wish to simply open a .txt file upon clicking on a button.
EDIT : When I say open a .txt file, I mean open it in some editor on the device, not open it asnd save it's content to some string in my app. Kind of like opening a browser to access a website from the app.
Here's the code I currently have (C#) :
private void ShowTextFile(string fileName)
{
Application.OpenURL(Application.streamingAssetsPath + "/PATH/" + fileName);
}
But it's not working ! What am I missing ?
EDIT : I'm expecting for the .txt file to open in another window (like opening a web browser, for example), but it simply isn't doing anything. Not even getting an error.
EDIT2 : I tried using Application.persistentDataPath instead, and in both cases, it says my .txt file doesn't exist. However, when using Application.persistentDataPath, it opens up a message box asking me what I want to open the file with. Whatever I choose, it will give me an error, telling me error loading file or something like that. I've also noticed that it opens "file:///". Is it normal that there is a file:/// before the path ?
EDIT3 (I'm on fire !) : I think the problem might be related to the fact that there is a "." in my path (the com.me.myapp in the data path). Is there any way to avoid this ? Am I even looking at the right path ?
I've tried opening a txt file on Android before, using this:
TextAsset txt = (TextAsset)Resources.Load("file", typeof(TextAsset));
string content = txt.text;
Where file is the name of the txt file (don't need to write file.txt).
The variable string will contain the contents of the text file, you just need to loop through them afterwards.
This method requires:
using System.Text;
using System.IO;
Put file.txt inside a directory named "Resources" (inside Assets dir), if it isn't there then create a new one.
This is my code for Android:
var rpath = Path.Combine(Application.streamingAssetsPath, "file_name");
WWW www = new WWW(rpath);
yield return www;
StringReader streamReader = new StringReader(www.text);
text = streamReader.ReadToEnd();
For iOS:
var rpath = Path.Combine(Application.streamingAssetsPath, "file_name");
StreamReader streamReader = new StreamReader(rpath);
text = streamReader.ReadToEnd();
Note: file_name in StreamingAssets folder
Found a solution that works ! Here's the thing, the streaming assets path, on Android, returns a path that can only be read by a WWW object. So I simply read it with a WWW object then recreated the file in my persistent data path. Added a check to make sure the file doesn't already exist before creating it. Also, make sure you create the directory in case it doesn't exist, else you'll get an error. Note that this solution is probably not optimal if you have large files that are regularly accessed.
string realPath = Application.persistentDataPath + "/PATH/" + fileName;
if (!System.IO.File.Exists(realPath))
{
if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PATH/"))
{
System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PATH/");
}
WWW reader = new WWW(Application.streamingAssetsPath + "/PATH/" + realPath);
while ( ! reader.isDone) {}
System.IO.File.WriteAllBytes(realPath, reader.bytes);
}
Application.OpenURL(realPath);
If anyone has anything to add to this answer, feel free !
I have stored an audio file in the resources folder of my application but when I use the below path I get a file no found exception.
Can someone explain if this is the correct way to reference a file in resources or if I need to set the path differently?
This is the code that take the audio file as a parameter:
SoundPlayer player = new SoundPlayer("Resources/Audio/punchSound.wav");
player.Load();
player.Play();
You can use resource string:
var music = Properties.Resources.punchSound;
And then use SoundPlayer like this:
var player = new SoundPlayer(new MemoryStream(music));
I have created a text file to save the error in that created file. I have a button which, once pressed, generates an error which should be saved to the file. But if I press the button twice, it will overwrite the first error generated, because the contents of the file are overwritten. I want to generate a another separate file to save the new error. A new file should be generated for each new error.
Thanks in advance
Simple use: FileExists Method and then if it exists pick a new name. Alternatively you could just append to the file.
PSUDO:
public string checkFileName(string fileName){
if(File.Exists(fileName)){
/Pick a new one
newFileName= fileName + DateTime.Now.ToLongDateString()
return checkFileName(newFileName)
}
return fileName
}
This could be the perfect link for you How to Open and Append a log file
You can add time stamp in filename, in this case you would get new file each time.
private void SaveErrorMessage(string errorMessage)
{
string errorFile = null;
for( int x = 0; x < Int32.MaxValue; ++x )
{
errorFile = string.Format(CultureInfo.InvariantCulture, "error-{0}.txt", x);
if( !System.IO.File.Exists(errorFileTest) )
{
break;
}
}
File.WriteAllText(errorFile, errorMessage);
}
This will overwrite the last file after you've had Int32.MaxValue files, but that'll take a while.
An alternative (and probably better) approach would be to simply append to the file, rather than creating a new one.
You may also want to consider using a more robust logging solution, such as log4net.
Creating file in C# is probably what you're looking for.
So you want to generate a unique file name for each error that occurs in your program? Probably the easiest way to accomplish this is to use the date/time when the error occured to name the file. In the function where you are writing to the file you will want to name the file like this:
string filename = LogPath + DateTime.Now.ToString("yyyyMMdd.HHmmss") + ".err";
Where LogPath is the path to the folder you want to write the error files to.
string fName = Path.GetFileName(tempPaths[z]);
if (!File.Exists(subAch + fName))
{
File.Move(tempPaths[z], subAch + fName);
Console.WriteLine("moved!!! from " + tempPaths[z] + " tooooo ");
}
tempPaths is a list with all the image file paths. e.g. ./images/image4.jpg
subAch is a directory string.
I wish to get the file name of the file then move them to another directory. But with the code above i kept getting error: file is being used by other process.
Is there anyway which get the file name and move them? I have tried fileStream but was confused by it.
Please advice.
Thank you!
Your code should work just fine. You just need to figure out who is locking the files.
I'd put the code inside the if-block in a try-catch block to deal with the locked files.
I will also recommend you to use Path.Combine instead of dir + file.
One thing: you are checking if subAch + tempPaths[z] exists, yet you are copying to a different location; subAch + fName.
File is being used by another process means exactly that. Someone/something is already using the file, so can't move it. You can always catch the error and moving everything else?
I have use a non-ideal way to grab the file name and move the files to another place.
tempPaths.AddRange(Directory.GetFiles(rawStorePath, filter, SearchOption.AllDirectories));
The code above gets all the directories of all the files in the folder set. The outcome with be something like this. tempPaths is a List.
"./images/glass_numbers_5.jpg"
"./images/G.JPG"
"./images/E.JPG"
"./images/F.JPG"
"./images/glass_numbers_0.jpg"
"./images/C.JPG"
"./images/B.JPG"
"./images/A.JPG"
"./images/D.JPG"
"./images/glass_numbers_7.jpg"
then after i use a loop to grab the file names.
for (int i = 0; i < tempPaths.Count; i++)
{
//Getting the original names of the images
int pLength = rawStorePath.Length;
string something = tempPaths[i].Remove(0, pLength);
if (!_tfileName.ContainsKey(tempPaths[i]))
{ _tfileName.Add(tempPaths[i], something); }
}
rawStorePath is the path of the targeted path e.g.: ./images/
tempPath[i] e.g. : ./images/G.JPG
So with the length i remove the letters and get the file name back.
Please advice me for a ideal way to do this if there is any.
Thanks!