C# 在C中读取txt文件
我有一个.aspx页面,代码隐藏文件中有一些C代码 我想在命令提示符下执行一个命令,并将输出保存到.txt文件中。这将起作用,并创建一个新的.txt文件 然后我想从.txt文件中读取第一行,并将字符串存储在变量中 我当前的代码如下,但是,它抛出了无法读取的文件。我的代码中的错误消息。这是为什么?我如何解决 更新: 因此,我修改了我的原始帖子中的代码,并在阅读之前添加了一个检查,以查看“archivo_resultado”是否存在。但是,调试视图输出C# 在C中读取txt文件,c#,asp.net,streamreader,C#,Asp.net,Streamreader,我有一个.aspx页面,代码隐藏文件中有一些C代码 我想在命令提示符下执行一个命令,并将输出保存到.txt文件中。这将起作用,并创建一个新的.txt文件 然后我想从.txt文件中读取第一行,并将字符串存储在变量中 我当前的代码如下,但是,它抛出了无法读取的文件。我的代码中的错误消息。这是为什么?我如何解决 更新: 因此,我修改了我的原始帖子中的代码,并在阅读之前添加了一个检查,以查看“archivo_resultado”是否存在。但是,调试视图输出 "archivo_resultado does
"archivo_resultado doesn't exist."
因此,当然,试图读取它会抛出一个错误
在命令提示符中执行以下命令的最有效方式是什么:
'ejecutable_CheckMac + " " + archivo_temporal'
并将输出字符串存储在变量中并保存到文件archivo_resultado
代码:
引发了什么异常?@MrTree无法读取该文件。您可以使用LINQ轻松读取第一行。缺少最重要的信息。两个变量archivo_resultado和archivo_temporal的值是多少?这不就是您要记录的吗?
string ejecutable_CheckMac = "C:\\inetpub\\wwwroot\\cgi-bin\\tbk_check_mac.exe";
var archivo_temporal = "C:\inetpub\wwwroot\cgi-bin\log\DatosParaCheckMac_100942.txt";
var archivo_resultado = "C:\inetpub\wwwroot\cgi-bin\log\ResultadoCheckMac_100942.txt";
System.Diagnostics.Debugger.Log(0, null, "Declare cmd variable.");
string cmd = ejecutable_CheckMac + " " + archivo_temporal + " > " + archivo_resultado;
System.Diagnostics.Debugger.Log(0, null, "cmd: " + cmd);
System.Diagnostics.Debugger.Log(0, null, "Start cmd execution.");
System.Diagnostics.Process process = new System.Diagnostics.Process();
var startInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + cmd);
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
System.Diagnostics.Process.Start(startInfo);
if (File.Exists(archivo_resultado))
{
System.Diagnostics.Debugger.Log(0, null, "archivo_resultado exists.");
}
else
{
System.Diagnostics.Debugger.Log(0, null, "archivo_resultado doesn't exist.");
}
string returnedLine = "";
try
{
System.Diagnostics.Debugger.Log(0, null, "Start - StreamReader to read archivo_resultado: " + archivo_resultado);
using (StreamReader sr = new StreamReader(archivo_resultado))
{
returnedLine = sr.ReadLine() ?? "";
Console.WriteLine(returnedLine);
System.Diagnostics.Debugger.Log(0, null, "archivo_resultado: " + returnedLine);
}
System.Diagnostics.Debugger.Log(0, null, "Finished - StreamReader to read archivo_resultado: " + archivo_resultado);
}
catch (Exception Ex2)
{
System.Diagnostics.Debugger.Log(0, null, "The file could not be read.");
Console.WriteLine(Ex2.Message);
}
string checkMacOutcome = "";
var psi = new System.Diagnostics.ProcessStartInfo(ejecutable_CheckMac, archivo_temporal);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
using (var proc = System.Diagnostics.Process.Start(psi))
{
using (StreamReader sr = proc.StandardOutput)
{
checkMacOutcome = sr.ReadToEnd();
}
}
StreamWriter writetext = new StreamWriter(archivo_resultado);
writetext.WriteLine(checkMacOutcome);
writetext.Close();