question

HemanthB-9452 avatar image
0 Votes"
HemanthB-9452 asked karenpayneoregon answered

Creating a seperate file again and again C#

Hi, I created a notepad and added an automatic backup to the file if the user does not save it. The code is given below:
private void timer1_Elapsed(object sender, EventArgs e) { System.IO.File.WriteAllText(@"C:\Users\bnara\Documents\Recoveredfile.txt", richTextBox1.Text); timer1.Start(); }

But that code is overwriting the "Recovered file.txt" every time I open a new Notepad app. I want that code to keep creating new backup files every time the user opens a new Notepad.

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

DuaneArnold-0443 avatar image
0 Votes"
DuaneArnold-0443 answered

You can get the system's date and time, format it to string and apply it to the file name to get file seperation. You can add a few seconds to the time in case the back up is done within the time frame repeatedly.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

$$ANON_USER$$ avatar image
0 Votes"
$$ANON_USER$$ answered

Hello,

You can try this code:

 private void timer1_Elapsed(object sender, EventArgs e)
     { 
          string[] Files = 
          System.IO.Directory.GetFiles(@"C:\Users\bnara\Documents\");
          System.IO.File.WriteAllText(@"C:\Users\bnara\Documents\Recoveredfile" + 
          Files.Length + ".txt", richTextBox1.Text);
          timer1.Start(); 
     }

I hope it helps.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

SimpleSamples avatar image
0 Votes"
SimpleSamples answered

You do not say how you want to manage the files. I assume you want the files to continue to exist after the program closes. You will need to have a way to do a cleanup of them. You also do not say what directory you want to use; you can use the user's temporary directory but maybe you want to use the documents directory or the ProgramData directory. The following are useful for generating temporary files.

The following is something I did to generate a temporary filename myself; I forget why I did it this way instead of using GetTempFileName.

 String BackupFilename = Path.GetTempPath() + '\\' + MakeBaseName() + ".tmp";

 String MakeBaseName()
 {
     Byte[] ByteArray = BitConverter.GetBytes(DateTime.Now.Ticks);
     // The '=' and '/' are valid for file names, but we will remove/replace anyway
     return Convert.ToBase64String(ByteArray).TrimEnd('=').Replace('/', '_');
 }




5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered

Here is some code that may help which I wrote for someone else so it may not suit your needs as each call to the code below creates a new file.

Create a file, replace the empty string with whatever

 File.WriteAllText(Operations.NextFileName(), "");


Are there any recovery files?

 if (Operations.HasAnyRecoveryFiles())
 {
     var lastFileName = Operations.GetLast();
 }

Remove all recovery files

 Operations.RemoveAllRecoveryFiles();


Full source

 using System;
 using System.Diagnostics;
 using System.IO;
 using System.Linq;
 using System.Security;
 using System.Text;
 using System.Threading.Tasks;
    
 namespace FileLibrary
 {
    
     public class Operations
     {
    
    
         private static readonly string _pattern = " _{0}";
         private static string _baseFileName => "Recoveredfile";
         /// <summary>
         /// Wrapper for <seealso cref="NextAvailableFilename"/> to obtain next available
         /// file name in a specific folder
         /// </summary>
         /// <returns>Unique ordered file name</returns>
         /// <remarks>
         /// Path is set to main assembly location with a base name of Import.txt
         /// </remarks>
         public static string NextFileName() => 
             NextAvailableFilename(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{_baseFileName}.txt"));
    
         /// <summary>
         /// Wrapper for <see cref="GetNextFilename"/>
         /// </summary>
         /// <param name="path"></param>
         /// <returns></returns>
         public static string NextAvailableFilename(string path)
         {
    
             if (!File.Exists(path) && Path.GetFileName(path).All(char.IsLetter))
             {
                 return path;
             }
                
             return Path.HasExtension(path) ?
                 GetNextFilename(path.Insert(path.LastIndexOf(Path.GetExtension(path), 
                     StringComparison.Ordinal), _pattern)) :
                 GetNextFilename(path + _pattern);
                
         }
         /// <summary>
         /// Work horse for <seealso cref="NextFileName"/>
         /// </summary>
         /// <param name="pattern"></param>
         /// <returns></returns>
         private static string GetNextFilename(string pattern)
         {
             string tmp = string.Format(pattern, 1);
    
             if (tmp == pattern)
             {
                 throw new ArgumentException("The pattern must include an index place-holder", nameof(pattern));
             }
    
             if (!File.Exists(tmp))
             {
                 return tmp;
             }
    
             int min = 1, max = 2;
    
             while (File.Exists(string.Format(pattern, max)))
             {
                 min = max;
                 max *= 2;
             }
    
             while (max != min + 1)
             {
                 int pivot = (max + min) / 2;
                    
                 if (File.Exists(string.Format(pattern, pivot)))
                 {
                     min = pivot;
                 }
                 else
                 {
                     max = pivot;
                 }
             }
    
             return string.Format(pattern, max);
         }
    
    
         /// <summary>
         /// Strip characters from string
         /// </summary>
         /// <param name="input"></param>
         /// <returns></returns>
         public static string GetNumbers(string input) => 
             new string(input.Where(char.IsDigit).ToArray());
            
         /// <summary>
         /// Recovery files
         /// </summary>
         private static string[] RecoveryFiles => 
             Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, 
                 $"{_baseFileName}*.txt");
            
         /// <summary>
         /// Get last recovery file by int value
         /// </summary>
         /// <returns></returns>
         public static string GetLast()
         {
             var result = RecoveryFiles
                 .Select(x => new {Name = x, Number = Convert.ToInt32(GetNumbers(Path.GetFileName(x))) })
                 .OrderByDescending(x => x.Number).FirstOrDefault();
    
             return result?.Name;
         }
    
         /// <summary>
         /// Determine if there are any recovery files
         /// </summary>
         /// <returns></returns>
         public static bool HasAnyRecoveryFiles() =>
             RecoveryFiles.Length >0;
    
         /// <summary>
         /// Remove all recovery files
         /// </summary>
         public static void RemoveAllRecoveryFiles()
         {
             if (HasAnyRecoveryFiles())
             {
                 foreach (var file in RecoveryFiles)
                 {
                     File.Delete(file);
                 }
             }
         }
     }
 }


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.