Search Unity

Question is there a way to read filename but ignore reapeted part of name

Discussion in 'Scripting' started by melonhead, Feb 3, 2024.

  1. melonhead

    melonhead

    Joined:
    Jun 3, 2014
    Posts:
    630
    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.

    im a bit stuck thanks
     
  2. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,996
    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".
     
    CodeSmile, CodeRonnie and Ryiah like this.
  3. melonhead

    melonhead

    Joined:
    Jun 3, 2014
    Posts:
    630
    tried the wildcard get red error at that line

    error CS1501: No overload for method `Exists' takes `2' arguments


    i need to use System.IO.File.Exists

    been trying to find some info and looks like cant use exists with a wildcard is this true?
     
    Last edited: Feb 3, 2024
  4. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,527
    As the error suggests, File.Exists doesn't have an overload that takes 2 arguments:
    https://learn.microsoft.com/en-us/dotnet/api/system.io.file.exists?view=net-8.0

    @Owen-Reynolds didn't use File.Exists, they used Directory.EnumeratorFiles which does have an overload that takes these 2 arguments:
    https://learn.microsoft.com/en-us/d...y-enumeratefiles(system-string-system-string)

    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).
     
    angrypenguin, CodeRonnie and Ryiah like this.
  5. melonhead

    melonhead

    Joined:
    Jun 3, 2014
    Posts:
    630
    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
     
  6. melonhead

    melonhead

    Joined:
    Jun 3, 2014
    Posts:
    630
    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?

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System.IO;
    5.  
    6. public class newTest2 : MonoBehaviour {
    7.  
    8.     // Use this for initialization
    9.     void Start () {
    10.  
    11.  
    12.  
    13.  
    14. DirectoryInfo dir = new DirectoryInfo("C:/TESTPIC/");
    15. FileInfo[] info = dir.GetFiles( "*.img" );
    16. foreach ( FileInfo f in info )
    17. {
    18.     print ( "Found: " + f.Name );
    19. }
    20.      
    21.     }
    22.  
    23.  
    24. }
    How would i select a random file from the array to load
     
  7. CodeRonnie

    CodeRonnie

    Joined:
    Oct 2, 2015
    Posts:
    529
    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.
     
  8. melonhead

    melonhead

    Joined:
    Jun 3, 2014
    Posts:
    630
    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
     
  9. CodeRonnie

    CodeRonnie

    Joined:
    Oct 2, 2015
    Posts:
    529
  10. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    2,420
    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.

    Code (CSharp):
    1.  
    2. using System.IO;
    3.  
    4. string folder = @"C:/testFolder";
    5. string pattern = @"*.img";
    6.  
    7. foreach (string found in Directory.EnumerateFiles(folder, pattern))
    8. {
    9.     string justTheName = Path.GetFileNameWithoutExtension(found);
    10.     int number;
    11.     if (int.TryParse(justTheName, out number))
    12.     {
    13.         // found a valid number-only filename like 123.img
    14.         DoWhateverYouWantWithImageNumber(number, found);
    15.     }
    16. }
     
    Last edited: Feb 4, 2024
    CodeRonnie and Ryiah like this.
  11. melonhead

    melonhead

    Joined:
    Jun 3, 2014
    Posts:
    630
    getting red error

    error CS0117: `System.IO.Directory' does not contain a definition for `EnumerateFiles'

    changed EnumerateFiles to GetFiles, then if i print(number) i get a list of numbers, how can i pick one of the found files at random and load it
     
    Last edited: Feb 4, 2024
  12. melonhead

    melonhead

    Joined:
    Jun 3, 2014
    Posts:
    630
    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.
     
    Last edited: Feb 4, 2024
  13. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,527
    The filenames are strings.

    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:
    https://learn.microsoft.com/en-us/dotnet/api/system.io.directory?view=net-8.0

    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:
    https://learn.microsoft.com/en-us/dotnet/api/system.io.path?view=net-8.0

    Methods like Path.GetFileName - which gets filenames from paths:
    https://learn.microsoft.com/en-us/d...8.0#system-io-path-getfilename(system-string)

    Or Path.GetFileNameWithoutExtension - which gets filenames without extensions from paths:
    https://learn.microsoft.com/en-us/d...extension(system-readonlyspan((system-char)))

    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.
     
    CodeRonnie and Ryiah like this.
  14. melonhead

    melonhead

    Joined:
    Jun 3, 2014
    Posts:
    630
    still learning sorry, but thanks for your help
     
  15. melonhead

    melonhead

    Joined:
    Jun 3, 2014
    Posts:
    630
    still trying differnt ways to get a random path from the string array and cant seem to understand this atall

    string randomPath=(0,found.Length);

    print(randomPath);

    how is this wrong, going crazy and just getting more errors
     
  16. melonhead

    melonhead

    Joined:
    Jun 3, 2014
    Posts:
    630
    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

    tried this not working

    ranPICK= Random.Range (0, path.Length+1);
    Path.GetFileName(ranPICK);

    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
     
  17. samana1407

    samana1407

    Joined:
    Aug 23, 2015
    Posts:
    226
    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.

    Code (CSharp):
    1. using System.IO;
    2. using UnityEngine;
    3.  
    4. [RequireComponent(typeof(SpriteRenderer))]
    5. public class LoadImagesExample : MonoBehaviour
    6. {
    7.     void Update()
    8.     {
    9.         if (Input.GetMouseButtonDown(0))
    10.         {
    11.  
    12.             DirectoryInfo dir = new DirectoryInfo("C:/Images/");
    13.             FileInfo[] info = dir.GetFiles("*.png");
    14.  
    15.  
    16.             if (info.Length == 0)
    17.             {
    18.                 Debug.LogWarning(" :`( ");
    19.                 return;
    20.             }
    21.  
    22.             string filePath = info[Random.Range(0, info.Length)].FullName;
    23.  
    24.             byte[] fileData = File.ReadAllBytes(filePath);
    25.             Texture2D texture = new Texture2D(2, 2);
    26.             texture.LoadImage(fileData);
    27.  
    28.             Sprite newSprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
    29.             GetComponent<SpriteRenderer>().sprite = newSprite;
    30.  
    31.         }
    32.     }
    33. }
    34.  
     
  18. melonhead

    melonhead

    Joined:
    Jun 3, 2014
    Posts:
    630
    thank you, looks preety much like i need, i am sure i can pick through it to familiarize myself how it works
     
  19. melonhead

    melonhead

    Joined:
    Jun 3, 2014
    Posts:
    630
    @samana1407

    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?

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System.IO;
    5.  
    6.  
    7. [RequireComponent(typeof(AudioSource))]
    8. public class newTest10 : MonoBehaviour {
    9.  
    10.  
    11.  
    12. void Start(){
    13.  
    14.  
    15. countFiles();
    16.  
    17. }
    18.  
    19.  
    20. public void countFiles(){
    21.  
    22.  
    23.  
    24. DirectoryInfo dir = new DirectoryInfo("C:/myFiles");
    25.        FileInfo[] info = dir.GetFiles("*.img");
    26.        foreach (FileInfo f in info)
    27.        {
    28.          print(f);
    29.        }
    30.        myran = Random.Range(0,info.Length);
    31.  
    32.        print(myran);
    33. }
    34.  
    35.  
    36.  
    37.  
    38. }




    }[/code]
     
    Last edited: Feb 6, 2024
  20. samana1407

    samana1407

    Joined:
    Aug 23, 2015
    Posts:
    226
    It seems to me like you're just trolling everyone. In my previous message, there's code that loads a random image file.
     
  21. melonhead

    melonhead

    Joined:
    Jun 3, 2014
    Posts:
    630
    its ok now, i was getting a red error symbol with no writting in the console, was my own fault i had a line wrong, thank you again
     
  22. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,996
    I had to look it up, since that can't be right -- those 2's are the size. All this weird file stuff is to choose a set of 4 colors. And they're in img format, since why not. This thread is now officially hilarious.
     
    Nad_B likes this.
  23. Nad_B

    Nad_B

    Joined:
    Aug 1, 2021
    Posts:
    712
    If I'm not mistaken, that's the "official" way to load a Texture from a file in Unity, as you need to create the texture before loading the file (dumb, as the function should be a static one), and the constructor accepts only a width/height > 0, so people just do a new(1,1) or new(2,2)...
     
    halley, samana1407 and spiney199 like this.
  24. melonhead

    melonhead

    Joined:
    Jun 3, 2014
    Posts:
    630
    ok a question please, i have it all working as i wanted with your help i am using this below to get the directory to read the files

    1. DirectoryInfo dir = new DirectoryInfo("C:/Images/");
    2. FileInfo[] info = dir.GetFiles("*.img");
    i have the random working and it displays an image from the folder when i click the mouse, is there a way to stop it repeating the same image , i have tried to compare strings but it seems to ignore it and still sometimes chooses the same picture again to load, how would i get the index number of the loaded image from the directory to check if it gets picked again straight away,