【问题标题】:How to save the content of Textbox into a textfile如何将文本框的内容保存到文本文件中
【发布时间】:2012-09-27 09:26:41
【问题描述】:

我有一个包含一些内容的文本框。我还有一个按钮 (SAVE),可以打开 FileSaveDialog 并允许将内容保存在 .txt 文件中。

XAML:

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

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

视图模型:

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???
    }

我基本上需要的是读取文本框的内容,打开文件保存对话框并将其存储在要保存在我的系统中的文本文件中。

【问题讨论】:

    标签: wpf mvvm textbox openfiledialog


    【解决方案1】:

    试试这样的:

    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);
    }
    

    【讨论】:

    • 你应该检查ShowDialog是否返回true
    • 好的。在 MSDN 上就是这样,所以我一直认为这是理所当然的。
    【解决方案2】:

    使用SaveFileDialog,您可以按照这些思路做一些事情

    string fileText = ReadMessage; 
    
    SaveFileDialog dialog = new SaveFileDialog() 
    { 
        Filter = "Text Files(*.txt)|*.txt|All(*.*)|*" 
    }; 
    
    if (dialog.ShowDialog() == true) 
    { 
         File.WriteAllText(dialog.FileName, fileText); 
    } 
    

    【讨论】:

    • 可能要检查文件是否已经存在/是否要覆盖等......
    • 是的。它工作顺利:) 如何打开对话框以加载文本文件?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-03
    相关资源
    最近更新 更多