Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. generating random dummy files

generating random dummy files

Scheduled Pinned Locked Moved C#
helpquestionlounge
12 Posts 9 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    Shani Aulakh
    wrote on last edited by
    #1

    Hi All, Can anyone help me with a method that could generate random dummy files with extensions..(.txt, .log, .exe) in a specified folder?

    K L J A 4 Replies Last reply
    0
    • S Shani Aulakh

      Hi All, Can anyone help me with a method that could generate random dummy files with extensions..(.txt, .log, .exe) in a specified folder?

      K Offline
      K Offline
      Kristian Sixhoj
      wrote on last edited by
      #2

      Look at the System.IO.File.Create() method. http://msdn2.microsoft.com/en-us/library/system.io.file.create.aspx[^]

      Kristian Sixhoej


      "Failure is not an option" - Gene Kranz

      1 Reply Last reply
      0
      • S Shani Aulakh

        Hi All, Can anyone help me with a method that could generate random dummy files with extensions..(.txt, .log, .exe) in a specified folder?

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #3

        what's the folder's name? "My Homework"?

        S 1 Reply Last reply
        0
        • L Lost User

          what's the folder's name? "My Homework"?

          S Offline
          S Offline
          Shani Aulakh
          wrote on last edited by
          #4

          Folder name could be anything...doesn't matter i can change that :P I have the following code.. private void button1_Click(object sender, EventArgs e) { StreamWriter outStream = null; string filename = "output.txt"; string message = null; try { outStream = new StreamWriter(filename); outStream.WriteLine("Hello World"); outStream.Close(); MessageBox.Show(filename); } catch (IOException e1) { message = "Unable to create " + filename + "\r\n"; message += String.Format("Reason: {0}", e1.Message); MessageBox.Show(message); return; } message = ("File successfully created"); } But, this just creates one txt file...Basically, right now I am working with windows application...I have written a program that can delete files from s specified folder older than X number of days, hrs, mins respectively..it works fine..But, i want to test this code thoroughly on a 'dummy' folder before ilet it loose on real data as deleting files in bulk makes me nervous! So, for that i want to create a method that would generete files for me with different extensions...files dont have to be empty... I know i can use for loop to create more files using my own code. But, I am just not sure how I am going to create files with different filter. Also, The problem with the dummy files is to get a decent spread of 'last modifed' times and i think the only practical way to achieve that is copy existing files from another folder which can be done programatically using File.Copy(). I suppose i could augment these by creating new files programatically with any extension i like and save them to disk using the StreamWriter class. But, I just want to use a different approach here and see if it actually works

          L M J 3 Replies Last reply
          0
          • S Shani Aulakh

            Folder name could be anything...doesn't matter i can change that :P I have the following code.. private void button1_Click(object sender, EventArgs e) { StreamWriter outStream = null; string filename = "output.txt"; string message = null; try { outStream = new StreamWriter(filename); outStream.WriteLine("Hello World"); outStream.Close(); MessageBox.Show(filename); } catch (IOException e1) { message = "Unable to create " + filename + "\r\n"; message += String.Format("Reason: {0}", e1.Message); MessageBox.Show(message); return; } message = ("File successfully created"); } But, this just creates one txt file...Basically, right now I am working with windows application...I have written a program that can delete files from s specified folder older than X number of days, hrs, mins respectively..it works fine..But, i want to test this code thoroughly on a 'dummy' folder before ilet it loose on real data as deleting files in bulk makes me nervous! So, for that i want to create a method that would generete files for me with different extensions...files dont have to be empty... I know i can use for loop to create more files using my own code. But, I am just not sure how I am going to create files with different filter. Also, The problem with the dummy files is to get a decent spread of 'last modifed' times and i think the only practical way to achieve that is copy existing files from another folder which can be done programatically using File.Copy(). I suppose i could augment these by creating new files programatically with any extension i like and save them to disk using the StreamWriter class. But, I just want to use a different approach here and see if it actually works

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #5

            Ok you could put the extensions you want to create into an array and then use System.Random class to use a random Extension private string[] myExtensions[] = new string[]{"exe","txt","log","jpg","bmp"/*,...*/} to avoid the IOException saying "the file already exists" you could use a timestamp that is added to the Filename string myFileName = string.Format(@"{0}\someName_{1}.{2}",someFolder,System.DateTime.Now.Ticks,randomExtension); and finally, if you want to manipulate the Creation/Modification - Dates of a file, take a look at the `System.IO.FileInfo` Class greets M@u

            S 1 Reply Last reply
            0
            • L Lost User

              Ok you could put the extensions you want to create into an array and then use System.Random class to use a random Extension private string[] myExtensions[] = new string[]{"exe","txt","log","jpg","bmp"/*,...*/} to avoid the IOException saying "the file already exists" you could use a timestamp that is added to the Filename string myFileName = string.Format(@"{0}\someName_{1}.{2}",someFolder,System.DateTime.Now.Ticks,randomExtension); and finally, if you want to manipulate the Creation/Modification - Dates of a file, take a look at the `System.IO.FileInfo` Class greets M@u

              S Offline
              S Offline
              Shani Aulakh
              wrote on last edited by
              #6

              Thanks m@u. I can try what you said, But i think its much easier to get it done. I think i can do it the following way. Files are getting created in the executable path of windows application project. I want to give out my own path. how do i do that? private void button1_Click(object sender, EventArgs e) { StreamWriter outStream = null; string message = null; for (int i = 0; i < (10000); i++) { string filename = "output"; filename += i.ToString(); if (i % 3 == 0) {//multiple of three filename += ".txt"; } else if (i % 5 == 0) {//multiple of 5 filename += ".log"; } else { filename += ".dat"; } try { outStream = new StreamWriter(filename); outStream.WriteLine("Hello World"); Thread.Sleep(60000); outStream.Close(); } catch (IOException e1) { message = "Unable to create " + filename + "\r\n"; message += String.Format("Reason: {0}", e1.Message); MessageBox.Show(message); } }

              L 1 Reply Last reply
              0
              • S Shani Aulakh

                Thanks m@u. I can try what you said, But i think its much easier to get it done. I think i can do it the following way. Files are getting created in the executable path of windows application project. I want to give out my own path. how do i do that? private void button1_Click(object sender, EventArgs e) { StreamWriter outStream = null; string message = null; for (int i = 0; i < (10000); i++) { string filename = "output"; filename += i.ToString(); if (i % 3 == 0) {//multiple of three filename += ".txt"; } else if (i % 5 == 0) {//multiple of 5 filename += ".log"; } else { filename += ".dat"; } try { outStream = new StreamWriter(filename); outStream.WriteLine("Hello World"); Thread.Sleep(60000); outStream.Close(); } catch (IOException e1) { message = "Unable to create " + filename + "\r\n"; message += String.Format("Reason: {0}", e1.Message); MessageBox.Show(message); } }

                L Offline
                L Offline
                Luc Pattyn
                wrote on last edited by
                #7

                two comments: 1. that is NOT random at all 2. always show the entire exception, not just it's message part; you may miss essential info. :)

                Luc Pattyn [Forum Guidelines] [My Articles]


                Sorry for any delays in replying, I currently don't always get e-mail notifications.


                A 1 Reply Last reply
                0
                • S Shani Aulakh

                  Folder name could be anything...doesn't matter i can change that :P I have the following code.. private void button1_Click(object sender, EventArgs e) { StreamWriter outStream = null; string filename = "output.txt"; string message = null; try { outStream = new StreamWriter(filename); outStream.WriteLine("Hello World"); outStream.Close(); MessageBox.Show(filename); } catch (IOException e1) { message = "Unable to create " + filename + "\r\n"; message += String.Format("Reason: {0}", e1.Message); MessageBox.Show(message); return; } message = ("File successfully created"); } But, this just creates one txt file...Basically, right now I am working with windows application...I have written a program that can delete files from s specified folder older than X number of days, hrs, mins respectively..it works fine..But, i want to test this code thoroughly on a 'dummy' folder before ilet it loose on real data as deleting files in bulk makes me nervous! So, for that i want to create a method that would generete files for me with different extensions...files dont have to be empty... I know i can use for loop to create more files using my own code. But, I am just not sure how I am going to create files with different filter. Also, The problem with the dummy files is to get a decent spread of 'last modifed' times and i think the only practical way to achieve that is copy existing files from another folder which can be done programatically using File.Copy(). I suppose i could augment these by creating new files programatically with any extension i like and save them to disk using the StreamWriter class. But, I just want to use a different approach here and see if it actually works

                  M Offline
                  M Offline
                  Mark Churchill
                  wrote on last edited by
                  #8

                  Why don't you add a "move to archive" option? That would make your program more useful, and also make you less nervous ;)

                  Mark Churchill Director Dunn & Churchill Diamond Binding: Zero to Data Layer in 3 mins

                  1 Reply Last reply
                  0
                  • S Shani Aulakh

                    Folder name could be anything...doesn't matter i can change that :P I have the following code.. private void button1_Click(object sender, EventArgs e) { StreamWriter outStream = null; string filename = "output.txt"; string message = null; try { outStream = new StreamWriter(filename); outStream.WriteLine("Hello World"); outStream.Close(); MessageBox.Show(filename); } catch (IOException e1) { message = "Unable to create " + filename + "\r\n"; message += String.Format("Reason: {0}", e1.Message); MessageBox.Show(message); return; } message = ("File successfully created"); } But, this just creates one txt file...Basically, right now I am working with windows application...I have written a program that can delete files from s specified folder older than X number of days, hrs, mins respectively..it works fine..But, i want to test this code thoroughly on a 'dummy' folder before ilet it loose on real data as deleting files in bulk makes me nervous! So, for that i want to create a method that would generete files for me with different extensions...files dont have to be empty... I know i can use for loop to create more files using my own code. But, I am just not sure how I am going to create files with different filter. Also, The problem with the dummy files is to get a decent spread of 'last modifed' times and i think the only practical way to achieve that is copy existing files from another folder which can be done programatically using File.Copy(). I suppose i could augment these by creating new files programatically with any extension i like and save them to disk using the StreamWriter class. But, I just want to use a different approach here and see if it actually works

                    J Offline
                    J Offline
                    Jan R Hansen
                    wrote on last edited by
                    #9

                    you are re-inventing the wheel - check this CP article: http://www.codeproject.com/KB/files/deleteold.aspx[^] works briliantly :)

                    Do you know why it's important to make fast decisions? Because you give yourself more time to correct your mistakes, when you find out that you made the wrong one. Chris Meech on deciding whether to go to his daughters graduation or a Neil Young concert

                    1 Reply Last reply
                    0
                    • L Luc Pattyn

                      two comments: 1. that is NOT random at all 2. always show the entire exception, not just it's message part; you may miss essential info. :)

                      Luc Pattyn [Forum Guidelines] [My Articles]


                      Sorry for any delays in replying, I currently don't always get e-mail notifications.


                      A Offline
                      A Offline
                      Anonymous
                      wrote on last edited by
                      #10

                      Yeah, you might want to use a RNG to generate random numbers, which could be used directly or indirectly as the filename. I recommend a Mersenne Twister, the classes for which are on the web. I agree with No. 2 as well. Exceptions aren't always what they seem to be, so it's good to have any information you can get.

                      1 Reply Last reply
                      0
                      • S Shani Aulakh

                        Hi All, Can anyone help me with a method that could generate random dummy files with extensions..(.txt, .log, .exe) in a specified folder?

                        J Offline
                        J Offline
                        johannesnestler
                        wrote on last edited by
                        #11

                        Hi, Very nice Comments on that topic so far. Heres some program that does what you need: using System; using System.IO; class Program { static void Main(string[] args) { CreateRandomFile(@"C:\"); } static void CreateRandomFile(string folder) { Random rand = new Random(); string[] ext = new string[] { ".dat", ".txt", ".log" }; string filename = Path.Combine(folder, String.Format("RandFile_{1}.{2}", folder, DateTime.Now.Ticks, ext[rand.Next(0, 3)])); try { File.WriteAllText(filename, "This is a test file"); FileInfo info = new FileInfo(filename); info.CreationTime = new DateTime(1999, 1, 1, 1, 1, 1); info.Refresh(); } catch(IOException) { /* Put Exception-Handling here */ } } }

                        1 Reply Last reply
                        0
                        • S Shani Aulakh

                          Hi All, Can anyone help me with a method that could generate random dummy files with extensions..(.txt, .log, .exe) in a specified folder?

                          A Offline
                          A Offline
                          Ari123
                          wrote on last edited by
                          #12

                          I would suggest a much simpler approach, using .NET Framework built-in classes... using System; using System.IO; namespace RandomFileNames { class Program { static void Main(string[] args) { //choose any folder you like, I used MyDocuments string folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); CreateRandomFiles(folder, 10); } static void CreateRandomFiles(string folderName, int numberOfFiles) { string[] extensions = { ".txt", ".exe", ".pdf", ".log", ".xls", ".doc" }; int count = extensions.Length; string fileName; Random random = new Random(); for (int i = 0; i < numberOfFiles; i++) { //this uses the static method GetRandomFileName() //of the Path class try { fileName = Path.GetRandomFileName(); //change the extension to one of your choice fileName = Path.ChangeExtension(fileName, extensions[random.Next(count)]); //create the final file name fileName = Path.Combine(folderName, fileName); //create the file itself File.Create(fileName); } catch (Exception ex) { //handle exceptions here } } } } }

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups