在c#文件中写入值

Write values in file in c#

我正在尝试用 C# 将值写入文件。我正在尝试使用以下代码之一:

 using (StreamWriter writer = new StreamWriter("values.txt"))
 {
            writer.Write("Word");
            writer.WriteLine("word 2");
            writer.WriteLine("Line");
 }

我收到错误:Error the best overloaded method match for System.IO.StranWriter.StreamWriter(System.IO.Stream) 有一些无效参数。

或以下代码:

string path = @"values.txt";

if (!File.Exists(path))
{
     // Create a file to write to. 
     using (StreamWriter sw = File.CreateText(path))
     {
            sw.WriteLine("Hello");
            sw.WriteLine("And");
            sw.WriteLine("Welcome");
     }
}

我收到以下错误:The name 'File' does not exist in the current context。我什么时候失踪了?

编辑:基本上我尝试将 FIle 更改为 System.IO.File,但我收到以下消息:The type or namespace 'File' does not exist in the namespace System.IO(are you missing an assembly reference)。我的代码在一个函数中,我从 windows 应用程序中的 public MainPage() 函数调用。

EDIT2:我尝试遵循建议的重复项 post 的解决方案。我收到 await operator can only be used within an async method 的消息。

我建议

IO.File.WriteAllText(fileFullPath, stringBuilder.ToString());

...而不是 StreamWriter。

我看到的是你正试图在流对象中写入, 只需按照以下代码即可完成

 System.IO.File.AppendAllText(@"{Filepath}","your text");

请注意使用 WriteAllText 或 , 将用您的新值替换所有内容。

看起来您使用 StreamWriter 是正确的。如果没有任何帮助,请从头开始创建新的解决方案,控制台应用程序并粘贴此代码。它必须有效:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            using (StreamWriter writer = new StreamWriter("test.txt"))
            {
                writer.Write("Line 1");
                writer.WriteLine("Still line 1");
                writer.WriteLine("Line 2");
            }
        }
    }
}

明明在bin文件夹里找你test.txt文件

好的,我们不得不在这里猜测很多,但看起来您正在编写 Phone、商店或通用应用程序。

新的 Windows 运行时不会为您提供所有旧的同步 classes 和方法。

您的平台上没有 FileStream(string) 构造函数,也没有静态 IO.File class。