Click here to Skip to main content
15,901,368 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to write a forms app, when started should create a newfile1.txt, newfile2.txt ....newfile[n].txt, at a particular location. Here "n" is hard coded, and the interval at which the new file created is controlled by a thread.

I started this as forms app with two buttons, however when I run this its going to create a single file. Can anyone toss in ideas on how to code it. Thanks


FileInfo fi = new FileInfo(@"C:\abc\file123.txt");
DirectoryInfo di = new DirectoryInfo(@"C:\abc");
private void button1_Click_1(object sender, EventArgs e)
{
            if (!di.Exists)
            {
                di.Create();
            }
            if (!fi.Exists)
            {
                fi.Create().Dispose();
            }
} 
private void button2_Click(object sender, EventArgs e)
{
            fi.Delete();
 }
Posted
Comments
Sergey Alexandrovich Kryukov 24-Jul-11 15:14pm    
Why?!
--SA

1 solution

C#
DirectoryInfo di = new DirectoryInfo(@"C:\abc");
int n = 10;

private void button1_Click_1(object sender, EventArgs e)
{
    if (!di.Exists) di.Create(); // Just to make sure the directory is there
    for(int idx = 1; idx<=n; idx++)
    {
        // Create a new FileInfo for each file from file1 to filen
        FileInfo fi = new FileInfo(String.Format(@"C:\abc\file{0:d}.txt", idx));
        // If that file does not exist create it
        if (!fi.Exists) fi.Create().Dispose();
    }
}
private void button2_Click(object sender, EventArgs e)
{
    if (!di.Exists) di.Create(); // Paranoia check
    foreach(FileInfo fi in di.GetFiles()) fi.Delete(); // Delete all files found in our directory
}


That should do it!

Cheers!

—MRB
 
Share this answer
 
Comments
Venkat Krishna Turlapati 25-Jul-11 20:15pm    
wow. The code worked thanks a lot. This is one aspect of the module. I have a windows service inside a server which constantly pokes this directory for a new file. It's boring to manually create a new file..right..So, wanted to automate this process. Thanks a lot.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900