当我使用FileStream结合StreamWriter去写".log"后缀名的文件时,会报错,说访问被拒绝,代码如下:
               string path = HttpContext.Current.Server.MapPath("~/logs/"+DateTime.Now.ToString("yyyy-MM-dd")+"/");
               if(!Directory.Exists(path))                
                     System.IO.Directory.CreateDirectory(path);
               path = path + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
               System.IO.FileStream fs = new System.IO.FileStream(path,System.IO.FileMode.Append);
               System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
               sw.Write("订单没有会员号");
               sw.Close();
               fs.Close();
若只用StreamWriter= System.IO.File.AppendText(path)这个方法去写,则可以正确执行,代码如下:
               string path = HttpContext.Current.Server.MapPath("~/logs/"+DateTime.Now.ToString("yyyy-MM-dd")+"/");
               if(!Directory.Exists(path))                
                    System.IO.Directory.CreateDirectory(path);
               path = path + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
               System.IO.StreamWriter sw = System.IO.File.AppendText(path);
               sw.Write("订单没有会员号");
               sw.Close();
为什么在写".log"这样的文件时,会这样,写".txt"文件时,第一种方法却没问题,请教各位帮帮忙,谢谢...

解决方案 »

  1.   

    第一种方法和第二种有本质区别,虽然你第一种方法中按照System.IO.FileMode.Append打开的文件,但是文件当前指向开头,而不是末尾。而第二张方法,打开文件后,指向末尾。如果文件是空的,自然没问题,如果有内容,这里差别就出来了。自己断点跟踪下流的Position属性就知道了。
      

  2.   

    不会有程序在用,这是在新建的文件夹下创建文件。而且,如果有问题,那创建".txt"文件应该也会有问题啊,可是".txt"却没有.
      

  3.   

    System.IO.FileMode.Append不也是在原有文件后追加么,怎么会指向开头