简体   繁体   English

StreamWriter不会创建文本文件

[英]StreamWriter doesn't create a text file

I have writtten a code to Create & write a file.But It doen't create a file.There's no any compilation error.My folder hierachy is DesktopModules -> SMSFunction->SMSText.I need to create a text file inside the SMSText folder, 我写了一个创建和写入文件的代码,但是它没有创建文件。没有任何编译错误。我的文件夹层次结构是DesktopModules-> SMSFunction-> SMSText。我需要在SMSText文件夹中创建一个文本文件,

public void WriteToFile(  string source, int dest, string messageIn, string operatorNew)
{
    try{

    string directory = ResolveUrl("~/DesktopModules/SMSFunction/SMSText");
    //string directory = Server.MapPath("~/DesktopModules/SMSFunction/SMSText");
    string filename = String.Format("{0:yyyy-MM-dd}__{1}.txt", DateTime.Now);
    string path = Path.Combine(directory, filename);

    if (!File.Exists(filename))
    {

        using (StreamWriter str = File.CreateText(path))
        {
            str.WriteLine("msisdn: " + source);
            str.WriteLine("shortcode : " + dest);
            str.WriteLine("Message : " + messageIn);
            str.WriteLine("Operator :" + operatorNew);
            str.Flush();

        }
    }
    else if (File.Exists(filename))
    {

        using (var str = new StreamWriter(filename))

        {
            str.WriteLine("msisdn: " + source);
            str.WriteLine("shortcode : " + dest);
            str.WriteLine("Message : " + messageIn);
            str.WriteLine("Operator :" + operatorNew);
            str.Flush();
        }

    }

}
catch(Exception ex)
{
    Response.Write(ex.Message);
}


}

There is something wrong here: 这里有问题:

string filename = String.Format("{0:yyyy-MM-dd}__{1}.txt", DateTime.Now); . 

You call string.Format passing a format string that requires two parameters {0:yyyy-MM-dd} and {1} , but you give only one DateTime.Now . 您调用string.Format传递了一个格式字符串,该格式字符串需要两个参数{0:yyyy-MM-dd}{1} ,但是只给出了一个DateTime.Now When your code reaches that line raises a FormatException and jumps to the catch block exiting without writing anything to disk. 当您的代码到达该行时,将引发FormatException并跳转到catch块,而无需向磁盘写入任何内容。

EDIT: If you don't want to overwrite the contents of the file then you should use the overloaded constructor of StreamWriter that allows to Append to the existing file 编辑:如果您不想覆盖文件的内容,则应使用允许追加到现有文件的StreamWriter的重载构造函数

.....
else if (File.Exists(filename))  
{  
    using (var str = new StreamWriter(filename, true))  
    {
         ....

but I think that you don't need that check on File.Exists. 但我认为您不需要对File.Exists进行检查。 If you look carefully to the StreamWriter documentation you will see that the file is created when it doesn't exist. 如果仔细查看StreamWriter文档,您会发现该文件在不存在时已创建。 So the above code could really simplified to 所以上面的代码可以真正简化为

    using (var str = new StreamWriter(path, true))      
    {      
        str.WriteLine("msisdn: " + source);      
        str.WriteLine("shortcode : " + dest);      
        str.WriteLine("Message : " + messageIn);      
        str.WriteLine("Operator :" + operatorNew);      
        str.Flush();      
    }     

removing the unnecessary if blocks 删除不必要的if块

    private void SetPartnerTemplate()
        {
            var sb = new StringBuilder();
            widget.RenderControl(new HtmlTextWriter(new StringWriter(sb)));

            string setting = sb.ToString();

            string fileLoc = @"D:\sample1.txt";
            FileStream fs = null;
            if (!File.Exists(fileLoc))
            {
                using (fs = File.Create(fileLoc))
                {
                }
            }

            if (File.Exists(fileLoc))
            {
                using (StreamWriter sw = new StreamWriter(fileLoc))
                {
                    sw.Write(setting);
                }
            }
            if (File.Exists(fileLoc))
            {
                setting = File.ReadAllText(fileLoc);
            }
            else
            {
                Response.Write("<script language='javascript'>window.alert('File not found');</script>");
            }
            //after writing storing dat file to db

            //VoCServiceObj.SpSetWidgetRatingPartnerTemplate(setting, partnerid, productid);
        }
       protected void btnUpload_Click(object sender, EventArgs e)
           {
            var sb = new StringBuilder();
            widget.RenderControl(new HtmlTextWriter(new StringWriter(sb)));
            string setting = sb.ToString();
            string fileLoc = @"D:\Newsample.txt";
            FileStream fs = null;
            if (!File.Exists(fileLoc))
            {
                using (fs = File.Create(fileLoc))
                {
                }
            }
            if (File.Exists(fileLoc))
            {
                using (StreamWriter sw = new StreamWriter(fileLoc))
                {
                    sw.Write(setting);
                }
            }
            if (File.Exists(fileLoc))
            {
                setting = File.ReadAllText(fileLoc);
            }
            else
            {
                Response.Write("<script language='javascript'>window.alert('File not found');</script>");
            }

            FileStream st = new FileStream(fileLoc, FileMode.Open);
            byte[] buffer = new byte[st.Length];
            st.Read(buffer, 0, (int)st.Length);

            SqlConnection conn = new SqlConnection("Data Source=dsname;Initial Catalog=test;User ID=test;pwd=password");
            SqlCommand cmd1 = new SqlCommand();
            cmd1.Connection = conn;
            //OpenConnection(conn);
            conn.Open();
            SqlCommand cmd = new SqlCommand("INSERT INTO Files(Data) VALUES(@Data)", conn);


            //string commandText = "INSERT INTO Files VALUES(@Name, @ContentType, ";commandText = commandText + "@Size, @Data)";
            //cmd.CommandText = commandText;
            //cmd.CommandType = CommandType.Text;

            //cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 100);
            //cmd.Parameters.Add("@ContentType", SqlDbType.VarChar, 50);
            //cmd.Parameters.Add("@size", SqlDbType.Int);
            cmd.Parameters.Add("@Data", SqlDbType.VarBinary);

            //cmd.Parameters["@Name"].Value = "name";
            //cmd.Parameters["@ContentType"].Value = "contentType";
            //cmd.Parameters["@size"].Value = 5;
            cmd.Parameters["@Data"].Value = buffer;
            cmd.ExecuteNonQuery();

            SqlCommand command = new SqlCommand("select Data from Files", conn);
            byte[] buffer3 = (byte[])command.ExecuteScalar();

            FileStream fs2 = new FileStream(@"D:\op.txt", FileMode.Create);
            fs2.Write(buffer, 0, buffer.Length);
            fs2.Close();
            st.Close();
            conn.Close();
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM