Reputation: 1520
I am trying to traverse a directory with thousands of subdirectories. In each subdirectory there is a .nfo file.
D:\Test\
D:\Test\Dir1\
D:\Test\Dir1\file1.nfo
D:\Test\Dir2\
D:\Test\Dir2\file2.nfo
D:\Test\Dir3\
D:\Test\Dir3\file3.nfo
I am using Xdocument to parse some info from it, and I need to create a new file in the same location as the source .nfo file.
D:\Test\
D:\Test\Dir1\
D:\Test\Dir1\file1.nfo
NEW FILE: D:\Test\Dir1\info.nfo
D:\Test\Dir2\
D:\Test\Dir2\file2.nfo
NEW FILE: D:\Test\Dir2\info.nfo
D:\Test\Dir3\
D:\Test\Dir3\file3.nfo
NEW FILE: D:\Test\Dir3\info.nfo
I think I have all of the basic parts, but I can't figure out how to create the new file in the same location as the source file.
Here is what I have so far:
string strID = null;
string[] filesNFO = Directory.GetFiles(@"D:\Test\", "*.nfo", SearchOption.AllDirectories);
foreach(string file in filesNFO)
{
var doc = XDocument.Load(file);
strID = doc.Root.Element("id") == null ? "" : doc.Root.Element("id").Value;
FileStream fs = new FileStream("info.nfo", FileMode.Create);
StreamWriter info = new StreamWriter(fs);
info.Write("http://powerhostcrm.com/" + strID);
info.Close();
}
Upvotes: 0
Views: 227
Reputation: 26386
foreach(string file in filesNFO)
{
FileInfo info = new FileInfo(file);
string current_dir = info.DirectoryName;
string newFileBane = current_dir + @"\newfilename.nfo";
//open filestream
//write to filestream
}
Upvotes: 1
Reputation: 38335
The piece missing is where to save the new file to. If that's the case, take the file
from the filesNFO
and grab the directory. I'd also suggesting wrapping everything in using statements:
string strID;
string[] filesNFO = Directory.GetFiles( @"D:\Test\", "*.nfo", SearchOption.AllDirectories );
foreach( string file in filesNFO )
{
var doc = XDocument.Load( file );
strID = doc.Root.Element( "id" ) == null ? "" : doc.Root.Element( "id" ).Value;
string directory = Path.GetDirectoryName( file );
string infoNfo = Path.Combine( directory, "info.nfo" );
using( var fs = new FileStream( infoNfo, FileMode.Create ) )
using( var info = new StreamWriter( fs ) )
{
info.Write( "http://powerhostcrm.com/" + strID );
}
}
Upvotes: 2