我正在尝试将所有数据写入文本文件,除非我将string time = DateTime.Now.ToString("d");
string name = "MyName";
File.WriteAllText(time+name+"test.txt","HelloWorld");
放在文件名中,否则它正在运行。
当前代码如下所示:
File.WriteAllText()
我得到了这个例外:
未处理的类型' System.IO.DirectoryNotFoundException'发生在mscorlib.dll
但据我所知,<?php
$result = mysql_query("select id_domeniu, nume_domeniu, parent from domenii");
$menu = array(
'menus' => array(),
'parent_menus' => array()
);
while ($row = mysql_fetch_assoc($result)) {
//creates entry into menus array with current menu id ie. $menus['menus'][1]
$menu['menus'][$row['id_domeniu']] = $row;
//creates entry into parent_menus array. parent_menus array contains a list of all menus with children
$menu['parent_menus'][$row['parent']][] = $row['id_domeniu'];
}
function buildMenu($parent, $menu) {
$html = "";
if (isset($menu['parent_menus'][$parent])) {
$html .= "<ul>";
foreach ($menu['parent_menus'][$parent] as $menu_id) {
if (!isset($menu['parent_menus'][$menu_id])) {
$html .= "<li><a href='#'>" . $menu['menus'][$menu_id]['nume_domeniu'] . "</a></li>";
}
if (isset($menu['parent_menus'][$menu_id])) {
$html .= "<li><a href='#'>" . $menu['menus'][$menu_id]['nume_domeniu'] . "</a>";
$html .= buildMenu($menu_id, $menu);
$html .= "</li>";
}
}
$html .= "</ul>";
}
return $html;
}
?>
<!doctype html>
<html lang=''>
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="script.js"></script>
<title>Test</title>
</head>
<body>
<div id='cssmenu'>
<?php echo buildMenu(0, $menu);; ?>
</div>
</body>
<html>
方法应该创建一个新文件或覆盖已存在的文件。
有任何建议吗?
答案 0 :(得分:7)
您可能希望确保路径有效且日期时间字符串不包含无效字符:
string time = DateTime.Now.ToString("yyyy-MM-dd");
// specify your path here or leave this blank if you just use 'bin' folder
string path = String.Format(@"C:\{0}\YourFolderName\", time);
string filename = "test.txt";
// This checks that path is valid, directory exists and if not - creates one:
if(!string.IsNullOrWhiteSpace(path) && !Directory.Exist(path))
{
Directory.Create(path);
}
最后将数据写入文件:
File.WriteAllText(path + filename,"HelloWorld");
答案 1 :(得分:4)
Errh根据MSDN一个DateTime.Now.ToString(“d”)看起来像这样:6/15/2008(编辑:取决于你的本地文化,它可能会产生一个有效的文件名)
斜杠在文件名中无效。
答案 2 :(得分:3)
替换
string time = DateTime.Now.ToString("d");
File.WriteAllText(time+name+"test.txt","HelloWorld");
与
string time = DateTime.Now.ToString("yyyyMMdd_HHmmss"); // clean, contains time and sortable
File.WriteAllText(@"C:\yourpath\" + time+name + "test.txt","HelloWorld");
你必须指定整个路径 - 而不仅仅是文件名
答案 3 :(得分:1)
这是因为您的名称将解析为“7/29 / 2015MyNametest.txt”或其他包含无效字符的内容,具体取决于您的计算机文化。我给出的示例显然不是有效的文件路径。我们必须删除斜杠(/)。 Windows上的文件名不允许使用它们。
将this问题视为Windows和Linux上的综合文件命名指南。