afrobeats
afrobeats

Reputation: 9

Is there a way to write to multiple files in the same folder?

I have two folders with the same files in them. I'm trying to read from the files in one folder, "do stuff" and write to the files with the same name in the other.

I have tried File.WriteAllText but it gives me an exception unhandled error

System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\Users\test\Desktop\'.'

string[] files = Directory.GetFiles(sourceDirectory);
foreach (string file in files)
{
   StringBuilder newFile = new StringBuilder();
   string[] lines = File.ReadAllLines(file);
   foreach (string line in lines)
   {
     // do stuff
      newFile.Append(x);
   }
   File.WriteAllText(targetDirectory, newFile.ToString());
}

I want to make changes to all the files in the directory.

Upvotes: 1

Views: 475

Answers (2)

Martin Noreke
Martin Noreke

Reputation: 4146

Expanding on James answer, adding a check to see if the directory exists may solve your issue.

var fi = new FileInfo(file);
if(!fi.Directory.Exists)
     fi.Directory.Create()
File.WriteAllText(Path.Combine(targetDirectory, fi.Name), newFile.ToString());

Upvotes: 0

James Harcourt
James Harcourt

Reputation: 6389

You have forgotten to include the filename of the target file. Change the last part to:

var fi = new FileInfo(file);
File.WriteAllText(Path.Combine(targetDirectory, fi.Name), newFile.ToString());

This assumes that newFile.ToString() is actually what you want inside the target file :-)

Upvotes: 4

Related Questions