Writing to FIFO FILE, Linux & Mono(C#) - c#

I want to do what I wrote in the title. But I just simply can't get my head around it. I also googled everythng. I want to write strings to file of special type FIFO, created by mkfifo (I think). If there are any other suggestions how to do this, you are welcome.
static class PWM
{
static string fifoName = "/dev/pi-blaster";
static FileStream file;
static StreamWriter write;
static PWM()
{
file = new FileInfo(fifoName).OpenWrite();
write = new StreamWriter(file, Encoding.ASCII);
}
//FIRST METHOD
public static void Set(int channel, float value)
{
string s = channel + "=" + value;
Console.WriteLine(s);
write.Write(s);
// SECOND METHOD
// RunProgram(s);
}
//SECOND METHOD
static void RunProgram(string s)
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = true;
proc.StartInfo.FileName = "bash";
string x = "|echo " +s+" > /dev/pi-blaster";
Console.WriteLine(x);
proc.StartInfo.Arguments = x;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.Start();
// proc.WaitForExit();
}
}

SOLUTION!!!! PI-BLASTER WORKS :D :D (lost 2 days of life because of this)
write.flush was critical, btw.
namespace PrototypeAP
{
static class PWM
{
static string fifoName = "/dev/pi-blaster";
static FileStream file;
static StreamWriter write;
static PWM()
{
file = new FileInfo(fifoName).OpenWrite();
write = new StreamWriter(file, Encoding.ASCII);
}
//FIRST METHOD
public static void Set(int channel, float value)
{
string s = channel + "=" + value + "\n";
Console.WriteLine(s);
write.Write(s);
write.Flush();
}
}
}

Related

c# File1's text keeps replacing file2's when I run it

All I need is for file1 and file2 to show the text inside the file. File1 is working great! File2 not so much. I believe there is something wrong with how I wrote file2 being read. Because I made a class so that I can make file2's text go to another file called outputfile2, and even that isn't working.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
namespace RandomName
{
class Program
{
static void Main(string[] args)
{
string winDir =
"C:/Users/RandomPerson/Desktop/RandomName/bin/Debug/";
string fileName = "file1.txt";
StreamReader reader = new StreamReader(winDir + fileName);
string outputFileName = "upperfile" + fileName;
StreamWriter writer = new StreamWriter(outputFileName);
int n = 0;
string st = "";
string upperString = "";
int n2 = 0;
string st2 = "";
string upperString2 = "";
string fileName2 = "file2.txt";
StreamReader reader2 = new StreamReader(winDir + fileName2);
string outputFileName2 = "output" + fileName2;
StreamWriter writer2 = new StreamWriter(outputFileName2);
do
{
++n;
st = reader.ReadLine(); // read one line from disk file
Console.WriteLine("Line #" + n + ": " + st); // write to the console
writer.WriteLine(st); // write line to disk file instead, using WriteLine() method
upperString = upperString + "\n" + st; // append each line to the big string
}
while (!reader.EndOfStream);
do
{
++n2;
st2 = reader2.ReadLine(); // read one line from disk file
Console.WriteLine("Line #" + n2 + ": " + st2); // write to the
console
writer2.WriteLine(st2); // write line to disk file instead,
using WriteLine() method
upperString2 = upperString2 + "\n" + st2; // append each line
to the big string
}
while (!reader2.EndOfStream);
reader.Close();
writer.Close();
Console.WriteLine("\nHere is the entire file in a string:");
Console.WriteLine(upperString);
Console.WriteLine(upperString2);
UpperString b = new UpperString(upperString);
UpperString2 c = new UpperString2(upperString2);
Console.WriteLine("\nThe string in reverse case: ");
b.showReverseCase();
Console.WriteLine("\n");
c.readingFile2();
c.toNewFile2();
}
}
}
"b." is for another class that I have. I copied the code from that class into the "c." one, changing names of strings and such. And that didn't work. Which is why I think something is wrong somewhere in the main.
Here is the class
class UpperString2
{
private string upperString2;
public UpperString2() { }
public UpperString2(string c) { upperString2 = c; }
public void readingFile2()
{
string[] lines = System.IO.File.ReadAllLines("C:/Users/SomeName/Desktop/FolderName/bin/Debug/file2.txt");
System.Console.WriteLine("\nAnother Poem \n");
foreach (string line in lines)
{
// Use a tab to indent each line of the file.
Console.WriteLine(line);
}
}
public void toNewFile2()
{
using (StreamWriter writetext = new StreamWriter("outputfile2.txt"))
{
string newText = (upperString2.ToUpper()).ToString();
writetext.WriteLine(newText);
}
}
I am a bit new to SteamReader and SteamWriter, which is why I think I went wrong somehow with that. I'm not sure what though. Thank you anyone who can help me have the text in file2 show up without it being overwritten by file1's text!
The problem is "outputfile2" was already opened by reader2 in Main().
string fileName2 = "file2.txt";
StreamReader reader2 = new StreamReader(winDir + fileName2);
string outputFileName2 = "output" + fileName2; //<--outputfile2.txt
StreamWriter writer2 = new StreamWriter(outputFileName2)
Then it raises an exception when you try to open the same file for writting in toNewFile2():
public void toNewFile2()
{
using (StreamWriter writetext = new StreamWriter("outputfile2.txt"))
{
string newText = (upperString2.ToUpper()).ToString();
writetext.WriteLine(newText);
}
}
This happens because the object writer2 is still alive and locking the file in Main() and there's no using statement for disposing the object when no longer needed.
Since you have moved the code to a class, call that class instead.

Wrapper build errors when attempting to compile code

Ok so I completely re-wrote the code for this in an attempt to make this simpler. Now it is telling me that "Type or namespace definition, or end-of-file expected. I can only think my spacing is off or i'm missing a bracket, but when i try to add a bracket i get the same error. All I want to do is create simple wrapper for my EXE and its been very frustrating. Please if possible look at my code and tell me what i am doing wrong here. Any help is welcomed...
using System.IO;
//using Resources.resx;
namespace EXE_program
{
public class LaunchEXE
{
static void Main(string[] args)
{
string exeName = Path.Combine(Directory.GetCurrentDirectory(), "EntUpdate_v3.0.exe");
string argsLin = "";
int timeoutSeconds = 100;}
internal static string Run(string exeName, string argsLine, int timeoutSeconds)
{
StreamReader outputStream = StreamReader.Null;
string output = "";
bool success = false;
Process newProcess = new Process();
newProcess.StartInfo.FileName = exeName;
newProcess.StartInfo.Arguments = argsLine;
newProcess.StartInfo.UseShellExecute = false;
newProcess.StartInfo.CreateNoWindow = true; //The command line is supressed to keep the process in the background
newProcess.StartInfo.RedirectStandardOutput = true;
newProcess.Start();
return "\t" + output; }
}
}
}

How to repeatedly pass inputs and outputs between a C# Stream and a Python Script?

I'm trying to run a Python script from C# as a stream, and to repeatedly pass inputs and outputs between Python and the stream, using StreamWriter and StreamReader.
I can read and write, but apparently only once, and not multiple times. (Which is what I need.)
Hopefully, somebody can tell me what I'm doing wrong.
(I'm aware that I can probably do what I need to do by reading and writing to a file. However, I'd like to avoid this if I can, since using the Stream seems cleaner.)
Here's my C# code:
using System;
using System.Diagnostics;
using System.IO;
public class Stream_Read_Write
{
public static void Main()
{
string path = "C:\\Users\\thomas\\Documents\\Python_Scripts\\io_test.py";
string iter = "3";
string input = "Hello!";
stream_read_write(path, iter, input);
//Keep Console Open for Debug
Console.Write("end");
Console.ReadKey();
}
private static void stream_read_write(string path, string iter, string input)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "C:\\Python27\\python.exe";
start.Arguments = string.Format("{0} {1}", path, iter);
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
start.RedirectStandardInput = true;
start.CreateNoWindow = true;
using (Process process = Process.Start(start))
using (StreamWriter writer = process.StandardInput)
using (StreamReader reader = process.StandardOutput)
{
for (int i = 0; i < Convert.ToInt32(iter); i++)
{
Console.WriteLine("writing...");
writer.WriteLine(input);
writer.Flush();
Console.WriteLine("written: " + input + "\n");
Console.WriteLine("reading...");
string result = reader.ReadLine();
Console.WriteLine("read: " + result + "\n");
}
}
}
}
The Python code looks like this:
import sys
iter = int(sys.argv[1])
for i in range(iter):
input = raw_input()
print (input)
And this is the output that I get:
writing...
written: Hello!
reading...
Strangely, when I remove the loops from both Python and C#, it works.
(For one iteration)
writing...
written: Hello!
reading...
read: Hello!
end
It's not clear to me why this happens, or what the solution could be, so any help is much appreciated.
I found a solution to my problem. I'm not really sure why this works, though.
For C#:
using System;
using System.Diagnostics;
using System.IO;
public class Stream_Read_Write
{
public static void Main()
{
string path = "C:\\Users\\thomas_wortmann\\Documents\\Python_Scripts\\io_test.py";
string iter = "3";
string input = "Hello";
stream_read_write(path, iter, input);
//Keep Console Open for Debug
Console.Write("end");
Console.ReadKey();
}
private static void stream_read_write(string path, string iter, string input)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "C:\\Python27\\python.exe";
start.Arguments = string.Format("{0} {1}", path, iter);
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
start.RedirectStandardInput = true;
start.CreateNoWindow = true;
using (Process process = Process.Start(start))
using (StreamWriter writer = process.StandardInput)
using (StreamReader reader = process.StandardOutput)
{
for (int i = 0; i < Convert.ToInt32(iter); i++)
{
writer.WriteLine(input + i);
Console.WriteLine("written: " + input + i);
string result = null;
while (result == null || result.Length == 0)
{ result = reader.ReadLine(); }
Console.WriteLine("read: " + result + "\n");
}
}
}
}
And the python code looks like this:
import sys
def reverse(input):
return input [::-1]
iter = int(sys.argv[1])
for i in range(iter):
input = sys.stdin.readline()
print reverse(input)
sys.stdout.flush()
This is a conventional stream problem.
You have to “flush” the stream
(e.g. stdout.flush() , where stdout is a stream object)
in order to send the data
no matter in C# or in Python.
In C#, as I know, you have to execute stream.Close()
to complete the flush itself,
or you can wrap the stream with “using”
and it send the data when the brackets is closed.
Edit:
Btw, the stream is only available to one side at a time.

Read a file into a list by a class does not working

I wrote an android app with xamarin in c#, and I made an application class to manage the file with the data wich I want to load in a list.
The app class:
namespace soroksar_sc_stat
{
[Application]
public class GetDataClass : Android.App.Application
{
public GetDataClass (){}
private string filename = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData),"playerdata.txt");
private DirectoryInfo di = Directory.CreateDirectory(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData));
private FileStream myFile = new FileStream(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData),"playerdata.txt"), FileMode.Create);
public List<string> GetList()
{
StreamReader myReader = new StreamReader(this.myFile);
string line;
List<string> list = new List<string>();
while((line = myReader.ReadLine()) != null)
{
list.Add(line);
}
myReader.Close ();
list.Add ("Blabla");
return list;
}
public void SetNewData (string playerName, DateTime bornDate)
{
string newLine = playerName + " " + bornDate.ToString () + " 0 0 0 0";
StreamWriter myWriter = new StreamWriter(this.myFile);
myWriter.WriteLine(newLine);
myWriter.Close();
}
}
}
The activity which should show the list
namespace soroksar_sc_stat
{
[Activity (Label = "DataActivity")]
public class DataActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.DataLayout);
Button addbutton = FindViewById<Button> (Resource.Id.dataButton);
ListView lista = FindViewById<ListView> (Resource.Id.listView1);
GetDataClass dataList = new GetDataClass();
List<string> list = dataList.GetList();
addbutton.Click += delegate
{
Intent intent = new Intent(this, typeof(AddDataActivity));
this.StartActivity(intent);
};
}
}
}
The first one is the class for the reading. Now it is an empty file, but for the troubleshooting I added a string at the end of the reading. However if I start the emulator in the second activity (which code is the second one) the list does not have any item. I don't really know where the problem is, if someone could help me I would really appreciate it.
As mentioned previously in my comment, I think that because you aren't closing the streamreader correctly, it may be closing before ever writing to the file. The solution would be one of the following
public void SetNewData (string playerName, DateTime bornDate)
{
string newLine = playerName + " " + bornDate.ToString () + " 0 0 0 0";
using(StreamWriter myWriter = new StreamWriter(this.myFile))
myWriter.WriteLine(newLine);
}
public void SetNewData (string playerName, DateTime bornDate)
{
string newLine = playerName + " " + bornDate.ToString () + " 0 0 0 0";
StreamWriter myWriter = new StreamWriter(this.myFile);
myWriter.WriteLine(newLine);
myWriter.Flush();
myWriter.Close();
}
Please note: That the first way is my preferred way as it makes sure all cleanup is done correctly. Also you should use a using block for reading too
using(StreamReader myReader = new StreamReader(this.myFile))
{
string line;
List<string> list = new List<string>();
while((line = myReader.ReadLine()) != null)
{
list.Add(line);
}
}

how to make rar file of full folder using c#

I have a procedure for making .rar file.
Code
public static void RarFilesT(string rarPackagePath, Dictionary<int, string> accFiles)
{
string[] files = new string[accFiles.Count];
int i = 0;
foreach (var fList_item in accFiles)
{
files[i] = "\"" + fList_item.Value;
i++;
}
string fileList = string.Join("\" ", files);
fileList += "\"";
System.Diagnostics.ProcessStartInfo sdp = new System.Diagnostics.ProcessStartInfo();
string cmdArgs = string.Format("A {0} {1} -ep",
String.Format("\"{0}\"", rarPackagePath),
fileList);
sdp.ErrorDialog = true;
sdp.UseShellExecute = true;
sdp.Arguments = cmdArgs;
sdp.FileName = rarPath;//Winrar.exe path
sdp.CreateNoWindow = false;
sdp.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(sdp);
process.WaitForExit();
}
This producer needs an string array of file list for making rar file.
Can any one tell me how can i make rar of a complete folder with sub folders and files.
Sorry 1 mistake and i also need selected extension files from given folder.
Updated function
/// <summary>
/// Package files. (Build Rar File)
/// </summary>
/// <param name="rarPackagePath">Rar File Path</param>
/// <param name="accFiles">List Of Files To be Package</param>
public static string RarFiles(string rarPackagePath,
Dictionary<int, string> accFiles)
{
string error = "";
try
{
string[] files = new string[accFiles.Count];
int i = 0;
foreach (var fList_item in accFiles)
{
files[i] = "\"" + fList_item.Value;
i++;
}
string fileList = string.Join("\" ", files);
fileList += "\"";
System.Diagnostics.ProcessStartInfo sdp = new System.Diagnostics.ProcessStartInfo();
string cmdArgs = string.Format("A {0} {1} -ep1 -r",
String.Format("\"{0}\"", rarPackagePath),
fileList);
sdp.ErrorDialog = false;
sdp.UseShellExecute = true;
sdp.Arguments = cmdArgs;
sdp.FileName = winrarPath;//Winrar.exe path
sdp.CreateNoWindow = false;
sdp.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(sdp);
process.WaitForExit();
error = "OK";
}
catch (Exception ex)
{
error = ex.Message;
}
return error;
}
For this u can make rar with full folder path.
-r argument can recursive folder and files.
Thanks to bystander.
And also u can specify extension for packaging.
Ex.
string rarPackage = "E:/Backup.rar";
Dictionary<int, string> accFiles = new Dictionary<int, string>();
accFiles.Add(1, "D://*.txt");
accFiles.Add(2, "D://*.html");
accFiles.Add(3, "D://*.jpg");
RarFiles(rarPackage, accFiles);
Un-Rar
public static void UnrarFiles(string rarPackagePath, string dir)
{
System.Diagnostics.ProcessStartInfo sdp = new System.Diagnostics.ProcessStartInfo();
string cmdArgs = string.Format("X {0} * {1}",
String.Format("\"{0}\"", rarPackagePath),
String.Format("\"{0}\"", dir));
sdp.Arguments = cmdArgs;
sdp.ErrorDialog = true;
sdp.UseShellExecute = true;
sdp.CreateNoWindow = false;
sdp.FileName = rarPath;
sdp.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(sdp);
process.WaitForExit();
}
-r argument can recursive folder and files..
so you add "-r" to
string cmdArgs = string.Format("A {0} {1} -ep -r",
String.Format("\"{0}\"", rarPackagePath),
fileList);
Ashish, Thanks for posting this; it's very helpful to me, as I've been told at the last moment that some files I have to FTP are supposed to be RARed first.
But I'm curious -- why is accFiles a dictionary, rather than a string[] or a Collection? Microsoft suggests not to pass dictionaries in public APIs: http://msdn.microsoft.com/en-us/library/dn169389(v=vs.110).aspx
Also, using a StringBuilder would clean up building fileList. I'd suggest this:
public static string RarFiles(string rarPackagePath,
Collection<string> accFiles)
{
string error = "";
try
{
StringBuilder fileListBuilder = new StringBuilder();
foreach (var fList_item in accFiles)
{
fileListBuilder.Append("\"" + fList_item + "\" ");
}
string fileList = fileListBuilder.ToString();
... (no change from this point on)
}
Again, thanks -- it's really been very helpful to me. I hope my suggestions are helpful to you, as well.

Categories