3

I have a textbox which has some content. I also have a button (SAVE) which shud open the FileSaveDialog and allow the content to be saved in a .txt file.

XAML:

<TextBox Height="93" IsReadOnly="True" Text="{Binding Path=ReadMessage, Mode=TwoWay}" Name="MessageRead" />

<Button Content="Save" Command="{Binding Path=SaveFileCommand}" Name="I2CSaveBtn" />

ViewModel:

private string _readMessage = string.Empty;
    public string ReadMessage
    {
        get
        {
            return _readMessage;
        }
        set
        {
            _readMessage = value;
            NotifyPropertyChanged("ReadMessage");
        }
    }

public static RelayCommand SaveFileCommand { get; set; }

private void RegisterCommands()
    {            
        SaveFileCommand = new RelayCommand(param => this.ExecuteSaveFileDialog());
    }
private void ExecuteSaveFileDialog()
    {
        //What To Do HERE???
    }

What I basically need is to read the content of textbox, open a file save dialog and store it in a text file to be saved in my system.

H.B.
  • 166,899
  • 29
  • 327
  • 400
Owais Wani
  • 119
  • 1
  • 6
  • 14

2 Answers2

11

Using SaveFileDialog you could do something along these lines

string fileText = ReadMessage; 

SaveFileDialog dialog = new SaveFileDialog() 
{ 
    Filter = "Text Files(*.txt)|*.txt|All(*.*)|*" 
}; 

if (dialog.ShowDialog() == true) 
{ 
     File.WriteAllText(dialog.FileName, fileText); 
} 
Richard Friend
  • 15,800
  • 1
  • 42
  • 60
2

Try something like this:

SaveFileDialog saveFileDialog1 = new SaveFileDialog();
   saveFileDialog1.Filter = "Text file|*.txt";
   saveFileDialog1.Title = "Save an Image File";
   saveFileDialog1.ShowDialog();

   // If the file name is not an empty string open it for saving.
   if(saveFileDialog1.FileName != "")
   {
 System.IO.File.WriteAllText(saveFileDialog1.FileName, MessageRead.Text);
}
Aleksandar Stojadinovic
  • 4,851
  • 1
  • 34
  • 56