Click here to Skip to main content
15,899,754 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
make text file in MyDocuments
text file not be created

What I have tried:

C#
Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) , "Stopwatch Data"));

            var sb = new StringBuilder();
           

            foreach (var i in listBox2.Items)
            {
                sb.AppendLine(i.ToString());
                

            }
            string sb2 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
            File.WriteAllText(sb2+@"Stopwatch Data/userdata.text", sb.ToString());
Posted
Updated 23-Sep-19 12:43pm
Comments
Richard MacCutchan 21-Sep-19 3:17am    
After each string is created you need to display it, or use the debugger, to see exactly what you are creating.

Hi,

1. the code shown does not compile
2. once the compile error gets fixed, it runs and creates a file (Not where you expect it!)
3. you should not use + to combine path parts, that is what Path.Combine is for (and it may be useful to know it accepts more than two arguments!)
4. you should not compute the folder name twice
5. when you forget a "directory separator" (a slash) you get an unexpected file one level up in the file hierarchy
6. you should put experimental (or even all) code in a try/catch block and display and/or log to a file any exception that occurs
7. and finally simple problems like this should be easily solved by using the debugger: single-step the code, watch the variables, and find the problems.

:)
 
Share this answer
 
Comments
Member 14013003 21-Sep-19 7:53am    
thanks im using slash (/) and working

<3
This will create a file in the MyDocuments folder called userdata.text. File will be wrote to the Stopwatch Data folder, as I believe you were trying to do?

var dir = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Stopwatch Data")); 
/* Path.Combine combines two paths */

if (!Directory.Exists(dir)) /* Check if the directory exists */
Directory.CreateDirectory(dir); /*If it doesn't, we create it */

StringBuilder sb = new StringBuilder();

foreach (string Item in listBox2.Items)
{
    sb.AppendLine(Item); 
    /* Appends a new line with the item value from the listbox */
}

var file = Path.Combine(dir, "userdata.text"); /* Combine the directory with the file name */

File.WriteAllText(file, sb.ToString()); 
/* Write the file. If not exists, it will create it. If exists, it will overwrite it */
 
Share this answer
 
v2

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