ok so i am trying to read in files from a hdd folder, i have this part working but only if the files are numbered like this 01.img 02.img 03.img etc but how can i read just the number if i name the files like this 01 blahblah.img 02 dingdong.img 03 anything.img. i tried this line
if (System.IO.File.Exists(“C:/testFolder/01” + “” + “.img”))
but it just skips reading the file and only reads if i have the number only, how can i just ignore what is after the number but still read the .img extention.
Do you know about wildcards? I think you can use Directory.EnumerateFiles("C:/testFolder/", "*01.img") which gives you a list of the matches? Or there may be other ways using just “dir”.
As the error suggests, File.Exists doesn’t have an overload that takes 2 arguments:
@Owen-Reynolds didn’t use File.Exists, they used Directory.EnumeratorFiles which does have an overload that takes these 2 arguments:
This method doesn’t return true or false though, it enumerates all the files that match the pattern. You could slap the linq method .Any() on the end to see if any results came back (or any other method you might use to see if a collection has 1 or more elements).
if i explain what i am trying to do mayve you can help me out as i have a lot of code using if file exists at the moment,
i have an external folder that i can put image files into, at the moment i have to number the files 01.img 02.ing etc, my code then checks each numbered file exists, then selects a random one to load, , is there a way to not even have to number the files just have different names but read how many files are in the folder and select a random one to load without havin to check each one exists
so i am just trying this script to read the files in the folder and just print the names to console at the moment, are these names stored then in the fileinfo array?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
public class newTest2 : MonoBehaviour {
// Use this for initialization
void Start () {
DirectoryInfo dir = new DirectoryInfo("C:/TESTPIC/");
FileInfo[] info = dir.GetFiles( "*.img" );
foreach ( FileInfo f in info )
{
print ( "Found: " + f.Name );
}
}
}
How would i select a random file from the array to load
I think you are on the right track. I am not where I can look at my code base, but I have a class that looks through all files matching a certain filename prefix to remove old log files. I know it uses DirectoryInfo to get files with a wild card as you have done there. As far as selecting a random file, you can just use something like the Random class to get a random index into that array.
i am not sure how to get the path from the array, i tried an int and random range but just got an error cant convert float to int even though i was not using a float, i se in the print that the file names are stored into the array , if i could random retrieve the filename then add it to the folder path i think it might work, just having trouble with the random range retrieval from the array
Try this with the length of the array as the argument. Random.Next Method (System) | Microsoft Learn And then yes you should be able to use the Path class to build the path from the directory and file name.
Look, as with pretty much every language out there, a system class offers a rich set of features for combining and splitting pathnames. System.IO.Path does all this.
You struggled to combine your work with Owen-Reynolds’ solution because you think one function will do everything you want, and that’s just not how programming usually works. Each function does one thing.
Untested, but surely close.
using System.IO;
string folder = @"C:/testFolder";
string pattern = @"*.img";
foreach (string found in Directory.EnumerateFiles(folder, pattern))
{
string justTheName = Path.GetFileNameWithoutExtension(found);
int number;
if (int.TryParse(justTheName, out number))
{
// found a valid number-only filename like 123.img
DoWhateverYouWantWithImageNumber(number, found);
}
}
ok so its kind of getting there so i see it reads the number of the file say 01.img, now if the file was 01 johny.img or just johny.img how would i count the files in the folder, then select one at random to load, i am just having trouble getting my head around it thanks
ahh i just got this if i print( found) it will show the paths, ok so how would i select a random file by path to load.
Read in every filename in the directory as some collection you are familiar with, like an array. Directory.GetFiles is one of these functions that does that. You can check out the rest of the Directory class for other functions that do similar stuff:
Now you have an array of strings that are the full path’s for those files. You can look into various functions in the ‘Path’ class that can be used to manipulate those paths:
Methods like Path.GetFileName - which gets filenames from paths:
You can also use any other string manipulation or even regex to compare/manipulate/whatever your strings.
Combine these efforts to get what YOU want.
This is programming. You need to familiarize yourself with your tools to deduce the method to make it do the thing you want. We can’t read your mind on all the stipulations you need and you’ve changed the requirements on us up to the point. Some are numbers, some aren’t… what is going on?
First thing about programming:
You need to learn to describe your problem. If you can’t describe it for humans to understand, how do you expect to describe it to your computer via the programming language?
Second:
You need to be familiar with your tools. If you don’t know what your tools are, how do you expect to use them?
…
And hey, if you don’t want to put effort in and instead want us to just write for you the code that breaks the strings up exactly how you need. Go ask ChatGPT then.
can anyone help; apart from sacastic comments like you got to learn, i am trying, i have looked at the directory system get files get paths i just can not get it
i just cant seem to et it right, so i have the directory that stores the paths how do i select a random file path from the directory then get it to load, think it is driving me ******* mad
i can see if i use print(found) it will display a list of the paths in the console but how do i get one at random and load that img file
I tried to read this topic, but I still don’t understand if it’s necessary to filter file names in any other way or if it’s not needed anymore. In the code below, there’s a simple example of how to load a random image from a certain folder on the disk. Just add this code to any object in the scene, and that’s it. Start the game, and with a mouse click, a random image will be loaded and assigned to a sprite.
using System.IO;
using UnityEngine;
[RequireComponent(typeof(SpriteRenderer))]
public class LoadImagesExample : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0))
{
DirectoryInfo dir = new DirectoryInfo("C:/Images/");
FileInfo[] info = dir.GetFiles("*.png");
if (info.Length == 0)
{
Debug.LogWarning(" :`( ");
return;
}
string filePath = info[Random.Range(0, info.Length)].FullName;
byte[] fileData = File.ReadAllBytes(filePath);
Texture2D texture = new Texture2D(2, 2);
texture.LoadImage(fileData);
Sprite newSprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
GetComponent<SpriteRenderer>().sprite = newSprite;
}
}
}
tried the code, looked promising then started getting a red error symbol with no writing, this is happening at random, so i am trying to go right back and start again, so i have the code below which reads the file paths from the folder and i can display them in the console thats ok, i have also managed to get a random number from the directory but how do i get the path to the file of the result of the random number so i can pass the path to the load img code?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
[RequireComponent(typeof(AudioSource))]
public class newTest10 : MonoBehaviour {
void Start(){
countFiles();
}
public void countFiles(){
DirectoryInfo dir = new DirectoryInfo("C:/myFiles");
FileInfo[] info = dir.GetFiles("*.img");
foreach (FileInfo f in info)
{
print(f);
}
myran = Random.Range(0,info.Length);
print(myran);
}
}