Reputation: 45
i wrote this code , it ctreates folder named "Fitness50" each time but the text file is not created.i want to create textfile within this folder and then save values of an arraylist. so for i have tried this
DirectoryInfo myDir = new DirectoryInfo(@"E:");
ParentFolderName1 = "Fittness50";
myDir.CreateSubdirectory(ParentFolderName1);
myDir = new DirectoryInfo(ParentFolderName1);
ParentFolderName1 = "Fittness50";
myDir.CreateSubdirectory(ParentFolderName1);
FileName1 = "./" + "" + ParentFolderName1 + "" + "/" + "Fittness10" + "" + "" + PopulationID + "" + ".txt";
FileStream fs2 = new FileStream(FileName1, FileMode.Create, FileAccess.Write);
StreamWriter SW2 = new StreamWriter(fs2);
for (i = 0; i < AlTargetData.Count; i++)
{
SW2.WriteLine(AlTargetData[i]);
}
AlTargetData.Clear();
SW2.Close();
fs2.Close();
Upvotes: 0
Views: 1651
Reputation: 56697
Well, first of all, /
is not the preferred directory separator on Windows, but \
is. Just because /
happens to work, there's no reason to use it. Secondly, you're not creating the Fittness10
folder at all, but you're creating Fittness50
twice. And third, you're not writing the file to the folders you create, but to the current working directory .
.
Your code (or at least what I understand you want to achieve) can be shortened significantly to this:
string path = @"E:\Fittness50\Fittness10";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string fileName = Path.Combine(path, String.Format("{0}.txt", PopulationID));
File.WriteAllText(fileName, String.Join(Environment.NewLine, AlTargetData));
Please note that you should not consider writing to bin\debug
. There will be no bin\debug
on the end-user's machine. If the user installs your application, it will be most probably be installed in the Program Files
folder, which your application won't be allowed to write to. Instead, consider writing to a common location, like the ones you can chose from in Environment.GetFolderPath
.
Upvotes: 4