c #windows app将文本写入文件

时间:2015-01-31 22:19:16

标签: c# windows file streamwriter

使用以下代码

写入文本文件时遇到实际问题
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'的定义,并且没有可以找到接受类型'System.IO.StreamWriter'的第一个参数的扩展方法'Close'(你是否缺少using指令或汇编参考?)(这是关闭线)

如您所见,我有SYstem.io参考

任何我出错的想法?​​

任何帮助表示赞赏

标记

1 个答案:

答案 0 :(得分:2)

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