Save file without using file save dialog

I am working on this project and I am having a problem. Well here is what I need to do.

When the user clicks the "Save" button, writes the selected record to the file specified in txtFilePath (the absolute path is not relative), without trimming the values ​​inside and handle any exceptions that occur.

Ok, here is my code:

 private void Save_Click(object sender, EventArgs e)
    {

        string filePath = txtFilePath.Text;

        if (!File.Exists(filePath))
        {
            FileStream fs = File.Create(filePath);
            fs.Close();
        }

        using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                foreach (string line in employeeList.Items)
                {
                    sw.WriteLine(line);
                }
            }
        }
            }

Now, when I switch to my program and want to save something from the Employeeelist.text file so that it is not saved in the place where I save it. I don’t know if something is missing in my code or what, but that won’t save. Here is an example:

C:\employess\employeelist.txt . "", , .

, . , .

+3
4

:

  • , employeeeelist.txt ,
  • ,
  • , .
  • - , .
  • , Save_Click - ?

, :

string path = txtFilePath.Text;

// This text is added only once to the file.
if (!File.Exists(path)) 
{
    using (StreamWriter sw = File.CreateText(path)) 
    {
        foreach (var line in employeeList.Items)
            sw.WriteLine(line.ToString());
    }   
} 
else 
{
    using (StreamWriter sw = File.AppendText(path)) 
    {
        foreach (var line in employeeList.Items)
            sw.WriteLine(line.ToString());
    }
}

, , , .

+3

, , StreamWriter/FileStream. , :

public void Save_Click(object sender, EventArgs e)
{
    StreamWriter file = 
      new StreamWriter(txtFilePath.Text, true);//Open and append
    foreach (object item in employeeList.Items) {
       file.WriteLine(item.toString());
    }
    file.Close();
}

[]

txtFilePath employeeList, , , , GUI, ? (WAG)

, , , ( , )

+1

.Net Framework 4, :

private void Save_Click(object sender, EventArgs e)
{
        File.AppendAllLines(txtFilePath.Text, employeeList.Items);
}

, , , , .

0

(.. ), .

  • , ? , , .
  • If the user does not enter the full path, do you have a way to make it one (for example, just insert C: \ at the beginning)? Or at least you can say when there is no full path and reject the request?
-1
source

All Articles