c# windows 应用程序将文本写入文件

c# windows app writing text to file

使用以下代码写入文本文件时遇到实际问题

using HCP1.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.UI.Xaml.Media.Imaging;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Storage;
using System.Threading.Tasks;
using System.Text;
using System.Diagnostics;

private void imageview_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e)
    {
        var point = e.GetPosition(imageview);
        var  p1 = (int)point.X;
        var p2 = (int)point.Y;
        string stringVal1;
        string stringVal2;   
        stringVal1 = System.Convert.ToString(p1);
        stringVal2 = System.Convert.ToString(p2);
        Text3.Text = stringVal1;
        Text4.Text = stringVal2;

        if (p2 > 210 && p2 < 235 && p1 > 339 && p1 < 367) { 

            string dave = Environment.NewLine + Text3.Text + "," + Text4.Text;
            string path = @"C:\myfile.txt";
            StreamWriter sw = new StreamWriter(path);
            string bufferOne = dave;
            sw.Write(bufferOne);
            sw.Close();
            sw.Dispose();
            };
                }

完成双击后,它应该将文本块的内容保存到文件中,但我遇到了三个错误

'System.IO.StreamWriter.StreamWriter(System.IO.Stream)' 的最佳重载方法匹配有一些无效参数(这是在 Streamwriter 行)

无法从 'string' 转换为 'System.IO.Stream'(在同一行)

'System.IO.StreamWriter' 不包含 'Close' 的定义并且没有扩展方法 'Close' 可以找到接受类型 'System.IO.StreamWriter' 的第一个参数(你是否缺少一个 using指令或程序集引用?)(这是在关闭行)

如你所见,我有 SYstem.io 参考资料

我哪里出错了?

感谢任何帮助

马克

使用File.WriteAllText。它是一个静态方法,作用与打开、写入和关闭文件相同。请记住,代码越少,错误就越少。

  if (p2 > 210 && p2 < 235 && p1 > 339 && p1 < 367) 
  { 
        string dave = Environment.NewLine + Text3.Text + "," + Text4.Text;
        File.WriteAllText(@"C:\myfile.txt", dave);
  }