dubiwei123 2016-01-22 09:58 采纳率: 0%
浏览 2334

用C#向txt中循环写入,怎么才能不被覆盖?源代码如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.IO;

namespace 合体示例
{

class Program
{
    static void Main(string[] args)
    {
        File.Create(@"1.txt");
        File.Create(@"2.txt");
        File.Create(@"3.txt");
        File.Create(@"4.txt");
        int m = 0;//为找到起点时m为0,找到起点后m为1,以m的变化和找到起点c作为正式开始的标志;
        int i = 1;

        cc: Random example = new Random();
        int number = example.Next(0, 10);  //每一次运行都产生一个0-10的随机数;
        const int c = 0;    //寻找的起始点为0
        if ((number != c) & (m == 0))
            goto cc; //刚开始采集数据的时候寻找起点,找不到则继续寻找;
        else
        {
            m = 1; //找到起点令m=1;防止之后不是0时还在寻找起点,丢失数据;
           // int i = 1;
            //int sum=1;
            byte[] bydata;
            char[] chardata;
            try
            {
               // do
               // {
                FileStream afile = new FileStream(i + ".txt", FileMode.Append, FileAccess.Write);//打开相应文件;
                    chardata = number.ToString().ToCharArray();
                    bydata = new byte[chardata.Length];
                    Encoder a = Encoding.UTF8.GetEncoder();
                    a.GetBytes(chardata, 0, chardata.Length, bydata, 0, true);
                    afile.Seek(0, SeekOrigin.Begin);
                    afile.Write(bydata, 0, bydata.Length);
                    i++;
                    if (i == 5)
                    {
                        i = 1;
                        //sum++;
                    }
                    goto cc;


            }
            catch (IOException ex)
            {
                Console.WriteLine(" an IO exception has been thrown");
                Console.WriteLine(ex.ToString());
                //goto cc;
                return;

            }

        }

    }


}

}

  • 写回答

2条回答 默认 最新

  • 91program 博客专家认证 2016-01-22 10:51
    关注

    afile.Seek(0, SeekOrigin.Begin);
    修改为:
    afile.Seek(0, SeekOrigin.End);

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器