无法使用c#创建文​​件 [英] Unable to create a file using c#

查看:61
本文介绍了无法使用c#创建文​​件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

namespace SimpleLicense
{
    class Program
    {
        static void Main(string[] args)
        {
        
            string fileName = @"C:\\Temp\\abc.txt";

            try
            {
                // Check if file already exists. If yes, delete it. 
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                // Create a new file 
                using (StreamWriter sw = File.CreateText(fileName))
                {
                    sw.WriteLine("Installed Date: {0}", DateTime.Now.ToString());
                    sw.WriteLine("Thermo Licensing System file");
                    
                    DateTime newDate = DateTime.Now.AddDays(31);
                    sw.WriteLine("License Expires After"+newDate);
                    
                   // sw.WriteLine("Add ");
                   // sw.WriteLine("Done! ");
                }

                // Write file contents on console. 
                using (StreamReader sr = File.OpenText(fileName))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(s);
                    }
                }
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.ToString());
            }
        }
    }
}





大家好,



我已经编写了上面的程序来创建一个.txt文件到特定的目录。但是我无法创建文件。我甚至将路径改为字符串fileName = @ d:\\abc.txt; ,程序编译但是没有创建到该特定目录的文件。有没有人帮我弄清楚可能是什么错误?



谢谢



Hello Everyone,

I have written the above program to create a .txt file to a particular directory.But I am not able to create the file.I even changed the path to string fileName = @"D:\\abc.txt"; ,the program compiles but a file to that particular directory is not created.Would anyone help me to figure out what could be the error?

Thanks

推荐答案





问题在于这一行:

Hi,

The problem is on this line:
string fileName = @"C:\\Temp\\abc.txt";



尝试将其替换为:


Try to replace it with this:

string fileName = @"C:\Temp\abc.txt";





在普通字符串中你需要逃避 \ 进入 \\ 。但是你在文件名之前使用 @ ,所以你不需要这样做。



In a normal string you would need to escape \ into \\. But you're using @ before the file name, so you don't need to do that.


除了正确的解决方案1:



In addition to the correct Solution 1:

if (File.Exists(fileName)) // no need to do it
{
    File.Delete(fileName); // don't delete the file, if will be overwritten anyway
}





而且,不要使用 File.CreateText 等。相反,使用类似的东西:



And also, don't use File.CreateText and the like. Instead, use something like:

using (StreamWriter writer = new StreamWriter(fileName)) {
    writer.WriteLine(/* ... */);
    // ...
} // here, writer.Dispose() is automatically called





你将需要与读者做类似的事情。



-SA


这篇关于无法使用c#创建文​​件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆