This question already has answers here:
redirecting output to the text file c#
(3 answers)
Closed 7 years ago.
I have an answer set program (verified to work) which I would like to run within a C# console application. I want to redirect the output of that program to a text file which I can then read from later on. I tried:
string directory = #"C:\...\Clingo";
string clingoPath = "clingo.exe";
string inputPath = "Assignment2.lp";
string dataPath = "Data1.lp";
string outputPath = "result.txt";
string arguments = String.Format("1 \"{0}\" \"{1}\" >\"{2}\"", inputPath, dataPath, outputPath);
// Set the necessary properties for the process
ProcessStartInfo clingoProcessInfo = new ProcessStartInfo(clingoPath, arguments);
clingoProcessInfo.WorkingDirectory = directory;
clingoProcessInfo.UseShellExecute = false;
// Start the process
Process clingoProcess = Process.Start(clingoProcessInfo);
However, when run, I get the following error:
"***ERROR: (clingo): '>result.txt': could not open input file!"
I would like to know how to fix that.
using System.IO;
if (!File.Exists(outputPath))
{
FileStream fs = new FileStream(outputPath, FileMode.CreateNew);
}
//now do the rest of your stuff
Related
This question already has answers here:
File being used by another process after using File.Create()
(11 answers)
Closed 1 year ago.
After creating a file via File.Create, I want to read it afterwards with File.ReadAllText. However, I always get an exception that says that the process cannot access the file. Once the file is created, access works without problems.
So I assume that the file is not yet released by File.Create at the time where it should be read. How do I solve this? Below is my method.
public SettingsModel LoadSettings()
{
var _fullPath = FileHelper.GetFullPath(_fileName);
if (!File.Exists(_fullPath))
{
File.Create(_fullPath).Close();
}
var serializedSettings = File.ReadAllText(_fullPath);
var settings = JsonConvert.DeserializeObject<SettingsModel>(serializedSettings);
if (settings == null)
{
return new SettingsModel();
}
else
{
return settings;
}
}
You create an empty file to deserialize it afterwards. You can perform deserialization only if the file exists:
public SettingsModel LoadSettings()
{
var _fullPath = FileHelper.GetFullPath(_fileName);
var settings = File.Exists(_fullPath)
? JsonConvert.DeserializeObject<SettingsModel>(File.ReadAllText(_fullPath))
: new SettingsModel();
return settings;
}
My program saves user's input to a txt file on it's current location
TextWriter ts = new StreamWriter("url.txt");
ts.WriteLine(textBox2.Text.ToString());
ts.Close();
It reads that when application starts
if (File.Exists("url.txt")) {
TextReader tr = new StreamReader("url.txt");
readUrl = tr.ReadLine().ToString();
textBox2.Text = readUrl;
tr.Close();
}
I add this program to Windows startup with these code
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true)) {
key.SetValue("House Party Protocol", "\"" + Application.ExecutablePath + "\"");
}
I published it with ClickOnce and installed it to my computer. It starts at windows startup bu doesn't read txt file. When I open it manually it works. I think ClickOnce installation path and windows startup path are different. How should I change my startup code to avoid this
You could try to use a specific directory. For example, you could save the url.txt file to LocalApplicationData (the directory for application-specific data that is used by the current, non-roaming user).
static void Main(string[] args)
{
string inputText = string.Empty;
//string directory = Environment.CurrentDirectory;
string directory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string path = Path.Combine(directory, "url.txt");
if (File.Exists(path))
{
TextReader tr = new StreamReader(path);
string readUrl = tr.ReadLine().ToString();
inputText = readUrl;
tr.Close();
}
string text = "abc";
TextWriter ts = new StreamWriter(path);
ts.WriteLine(text);
ts.Close();
}
If you really want to use the directory where the application is running then you could try to use Environment.CurrentDirectory (commented-out in the sample code above). This might give you the same error you had before (when using relative path) but it might help you troubleshoot the issue by showing what directory it's trying to use.
Here's a list of other special folders:
Environment.SpecialFolder
How do I execute and return the results of a python script in c#?
I am trying to run a python script from my controller.
I have python.exe setup in a virtual environment folder created with the virtualenv command.
So just for testing purposes at the moment I would like to just return resulting string from my phython script:
# myscript.py
print "test"
And display that in a view in my asp.net mvc app.
I got the run_cmd function from a related stackoverflow question.
I've tried adding the -i option to force interactive mode and calling process.WaitForExit() with no luck.
namespace NpApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
ViewBag.textResult = run_cmd("-i C:/path/to/virtualenv/myscript.py", "Some Input");
return View();
}
private string run_cmd(string cmd, string args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = #"C:/path/to/virtualenv/Scripts/python.exe";
start.CreateNoWindow = true;
start.Arguments = string.Format("{0} {1}", cmd, args);
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
//Console.Write(result);
process.WaitForExit();
return result;
}
}
}
}
}
It seems like myscript.py never even runs. But I get no errors, just a blank variable in my view.
Edit:
I had tried to simplify the above stuff because I thought it would be easier to explain and get an answer. Eventually I do need to use a package called "nameparser" and store the result of passed name argument into a database. But if I can just get the run_cmd to return a string I think I can take care of the rest of it. This is why I think the rest api and IronPython mentioned in the comments may not work for me here.
Ok, I figured out what the issue was thanks to some leads from the comments. Mainly it was the spaces in the path to the python.exe and the myscript.py. Turns out I didn't need -i or process.WaitForExit(). I just moved the python virtual environment into a path without spaces and everything started working. Also made sure that the myscript.py file was executable.
This was really helpful:
string stderr = process.StandardError.ReadToEnd();
string stdout = process.StandardOutput.ReadToEnd();
Debug.WriteLine("STDERR: " + stderr);
Debug.WriteLine("STDOUT: " + stdout);
That shows the python errors and output in the Output pane in Visual Studio.
This question already has answers here:
Determining if file exists using c# and resolving UNC path
(6 answers)
Closed 8 years ago.
I'm using VLC to open video files in C# form application. In my code as you see below "File.Exists" always returns false, although the file exists in the given path. But, as seen in the commanded line, when I give the path manually the file gets opened. There's no problem in string.Format processing, I have checked it in debug mode many time, I get the right path from string.Format but still File.exists returns false.
1) Code
fileName = string.Format(#"\\192.168.12.25\secRecords\{6}\{7}\{0:00}{1:00}{2:00}\CAM{5}_{0:00}{1:00}{2:00}_{3:00}{4:00}.mp4", (dateTimePicker1.Value.Year % 100),
(dateTimePicker1.Value.Month),
dateTimePicker1.Value.Day,
dateTimePicker1.Value.Hour,
(dateTimePicker1.Value.Minute / 15) * 15, myStr[1], splittedIp[2], splittedIp[3]);
//fileName = #"\\192.168.12.25\secRecords\3\4\140617\CAM1_140617_1300.mp4";
if (File.Exists(fileName))
{
id = axVLCPlugin21.playlist.add(fileName);
trackBar1.Value = 0;
}
else
{
id = -1;
MessageBox.Show("File not found!");
}
fileName value in debug mode:
"\\\\192.168.12.25\\secRecords\\3\\4\\140617\\CAM1_140617_1300.mp4"
splittedIp[3] was finishing with an unknown (illegal) character RS, the problem is solved by removing the unknown character from string.
splittedIp[3] = splittedIp[3].Remove(splittedIp[3].Length - 1);
This question already has answers here:
File count from a folder
(12 answers)
how to display the statistics about all the files in a folder in C# [closed]
(1 answer)
Closed 9 years ago.
I'm writing an console application to show folder statistics on C:\windows, and show the total files in there is there anyways it can be simplified and link the file type with the user!. This is what I've got so far:
{
String extention = String.Empty;
// Prompt the user to enter extention type
Console.Write("Please enter extention type: ");
extention = Console.ReadLine();
// This gets the Folder location which in this case is C:\\windows
DirectoryInfo root = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Windows));
// This is basicly the bit that collects the data after the user has entered the extention type
FileInfo[] executables = root.GetFiles("*exe");
foreach (var exe in executables)
{
//This will show the word txt in the console window
Console.WriteLine(exe.Name);
}
}
}
}
{
String extention2 = String.Empty;
// Prompt the user to enter extention type
extention2 = Console.ReadLine();
// This gets the Folder location which in this case is C:\\windows
DirectoryInfo root2 = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Windows));
FileInfo[] text = root2.GetFiles("*.txt");
foreach (var txt in text)
{
//This will show the word txt in the console window
Console.WriteLine(txt.Name);
}
}
String extention4 = String.Empty;
// Prompt the user to enter extention type
extention4 = Console.ReadLine();
// This gets the Folder location which in this case is C:\\windows
DirectoryInfo root4 = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Windows));
FileInfo[] windows = root4.GetFiles("*.win");
foreach (var win in windows)
{
//This will show the word txt in the console window
Console.WriteLine(win.Name);
}
Try using: new DirectoryInfo("C:\\Windows")
If you want to get a list of the files in that directory then call:
EnumerateFiles("*",SearchOption.AllDirectories)
on the DirectoryInfo object
Look at this:
"How to: Get Information About Files, Folders, and Drives (C# Programming Guide)"
http://msdn.microsoft.com/en-us/library/6yk7a1b0.aspx
For example:
// Get the files in the directory and print out some information about them.
System.IO.FileInfo[] fileNames = dirInfo.GetFiles("*.*");
foreach (System.IO.FileInfo fi in fileNames)
{
Console.WriteLine("{0}: {1}: {2}", fi.Name, fi.LastAccessTime, fi.Length);
}
You can change the Console.WriteLine to the format that you want...
Update:
System.IO.DriveInfo di = new System.IO.DriveInfo(#"C:\");
// Get the root directory
System.IO.DirectoryInfo dirInfo = di.RootDirectory;
// And then you can do .GetFiles()
System.IO.FileInfo[] fileNames = dirInfo.GetFiles("*.*");