Streamwriter throws a system.argumentexception - c#

I know this question seems strange.
I use .NET Micro Framework to write a small program in C# that use the default emulator to emulate a flash light using 5 buttons on the emulator, using interruptport to raise events.
I coded so that when i pressed the bottom button, all the records stored in an arraylist usagelog will be printed out to a txt file. Very simple and straightforward, i made a Streamwriter instance
StreamWriter sw = new StreamWriter(#"c:\temp.txt");
But then it throws "An unhandled exception of type 'System.ArgumentException' occurred in System.IO.dll" at this line.
I can't fix this, and I can't understand why there's an argument exception here. The code works fine for a console project in visual C#, but it doesn't in Micro Framework.

The problem you are having is the because the FileSystem is different between Windows and the MicroFramework. I was able to get it to run on the Emulator by using some Directory Functions to determine the available directorys.
public static void Main()
{
string d = Directory.GetCurrentDirectory();
string[] directorys = Directory.GetDirectories(d);
foreach (var item in directorys )
{
Debug.Print(item);
}
try
{
using (StreamWriter sw = new StreamWriter("\\WINFS\\temp.txt"))
{
sw.WriteLine("Good Evening");
sw.Close();
}
}
catch (Exception ex)
{
throw ex;
}
}
In the Emulator I came up with
[0]: "\\ROOT"
[1]: "\\WINFS"
ROOT did not work but WINFS did.

Related

C# Azure Face AI try to recognize people in image

My goal is to check if the system know/don't know the person who is sitting in front of my webcam.
First I tried it in a Console App and everythink worked fine but now I what to have a "nice" operlay in WPF and I inplement all in my WPF App even a Anti UI Block System but now I get a exeption
I know thats a big exeption. I'm sorry that the exeption is written in German (I can't change it). What is says: System.Net.Http.HttpRequestException: Error while sending and the remotehost closed a connection.
Here is the methode that triggers that exeption:
private static async Task<List<DetectedFace>> DetectFaceRecognize(IFaceClient faceClient, string path, string recognition_model)
{
try
{
FileStream fs = File.OpenRead(path);
IList<DetectedFace> detectedFaces = await faceClient.Face.DetectWithStreamAsync(fs, detectionModel: DetectionModel.Detection03);//Exeption triggert here
Console.WriteLine($"{detectedFaces.Count} face(s) detected from image `{Path.GetFileName(path)}`");
fs.Close();
return detectedFaces.ToList();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
return await DetectFaceRecognize(faceClient, path, recognition_model);
}
}
Can someone help me with this exeption?
Can you explicitly set the TLS version by adding the following line
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

C# File.AppendText(path) Access to path denied

I know this is a common problem with a lot of related topics on here. But none of them seem to work for me.
I have code that works on a production system that I've copied across to my local home computer:
private static void WriteToLog(string logText, string logPath)
{
try
{
using (StreamWriter outputFile = File.AppendText(logPath))
{
outputFile.WriteLine(DateTime.Now.ToString() + "|| " + Regex.Replace(logText, #"\t|\n|\r", ""));
}
}
catch (IOException ex)
{
//what do?
throw ex;
}
}
The line using (StreamWriter outputFile = File.AppendText(logPath)) throws the classic exception:
System.UnauthorizedAccessException: 'Access to the path
'C:\Users\Jaso\Documents\DataChecker_Logs\schema_a-academic_attainment.txt'
is denied.'
At runtime the path variable contains "C:\\Users\\Jaso\\Documents\\DataChecker_Logs\\schema_a-academic_attainment.txt"
The Security of the folder in question looks like this:
When I find the user the process is run under using WindowsIdentity.GetCurrent().Name;, the value returned is "DESKTOP-LMMBET3\\Jaso" which according to the folder's settings (above screenshot) is a principal with full control!!
Windows 10 machine.
GRRR!!!
Check the permission of the file itself not the folder
if you don't have the permission to access the file this error will be thrown
System.UnauthorizedAccessException

ghostscript.net rasterizer 'gsapi_init_with_args' is made: -15 error

When I run this code:
var stream = File.OpenRead(#"C:\tmp\PdfToTest.PDF");
var latestVersion = GhostscriptVersionInfo.GetLastInstalledVersion();
rasterizer = new GhostscriptRasterizer();
rasterizer.Open(stream, latestVersion, false);
I am getting this error
An exception of type 'Ghostscript.NET.GhostscriptAPICallException' occurred in Ghostscript.NET.dll but was not handled in user code
Additional information: An error occured when call to 'gsapi_init_with_args' is made: -15
The error is in this line:
rasterizer.Open(stream, latestVersion, false);
Anyone could point me what it is causing this to happen?
I am running this in local machine. Installed the Ghostscript on Package manager console. Everything seems to be right, but it simple doesn't work.
-15 is a 'rangecheck' error. There should be considerable extra backchannel information which might give some useful details. However since you are not using Ghostscript directly I can't tell you where it might be going.
You should put the PDF file you are using as input somewhere public at least so we can look at it.
Ideally you should reproduce the problem with Ghostscript itself, from the command line, but in any event you must supply the configuration information (ie what settings you have used). The version of Ghostscript (and whether its 32 or 64 bit) would also be useful information.
I'm afraid there's nothing much anyone can do with what you've given us to go on.
This is my working example.
So I call the method ResizePDF(string filePath) and give the file path including extension (eg. C:\tmp\file.pdf) as parameter.
The method returns the memoryStream with the resized file that I can use to do whatever.
There are some work to do around it, however it is working so far.
internal MemoryStream ResizePDF(string filePath)
{
string inputFilePath = String.Format(#"{0}", filePath);
GhostscriptPipedOutput gsPipedOutput = new GhostscriptPipedOutput();
string outputPipeHandle = "%handle%" + int.Parse(gsPipedOutput.ClientHandle).ToString("X2");
MemoryStream memStream = null;
using (GhostscriptProcessor processor = new GhostscriptProcessor())
{
try
{
processor.Process(GetGsArgs(inputFile, outputPipeHandle));
byte[] rawDocumentData = gsPipedOutput.Data;
memStream = new MemoryStream(rawDocumentData);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
gsPipedOutput.Dispose();
gsPipedOutput = null;
}
}
return memStream;
}
private string[] GetGsArgs(string inputFilePath, string outputFilePath)
{
List<string> switches = new List<string>();
switches.Add("-empty");
switches.Add("-dQUIET");
switches.Add("-dSAFER");
switches.Add("-dBATCH");
switches.Add("-dNOPAUSE");
switches.Add("-dNOPROMPT");
switches.Add("-dPDFSETTINGS=/ebook");
switches.Add("-sDEVICE=pdfwrite");
switches.Add("-sPAPERSIZE=a4");
switches.Add("-sOutputFile=" + outputPipeHandle);
switches.Add("-f");
switches.Add(inputFilePath);
return switches.ToArray();
}
Thanks you all.

Reading local event log?

Here i am trying to read the local system event log using c# using this code-
string eventLogText = "";
try
{
var eventLog = new EventLog("logname", "machinename");
foreach (var entry in eventLog.Entries)
{
eventLogText += entry;
}
}
catch (Exception eg)
{
MessageBox.Show(eg.Message);
}
It is working well, but the problem is, in the variable eventLogText i get only System.Diagnostics.EventLogEntry repeatedly, may be this is very common mistake but i don't know what to do as i am very new to the c# as well as programming too.
Secondly i want to know that if a system is not logged in using Administrator account, in that case reading event log will cause any exception or error and if it will what will be the solution for it ?
Need help.Thanks in advance.
Regarding your first question, you are just adding the variable entry to the string, which is calling the ToString method on that variable. The default implementation of ToString is to return the name of the class. (Hence the repeated System.Diagnostics.EventLogEntryoutput)
You will need to use the members in the EventLogEntry class to retrieve the data you are interested in. For example, this console application will print the source and message of the first 10 entries in the Application event log:
static void Main(string[] args)
{
StringBuilder eventLogText = new StringBuilder();
try
{
var eventLog = new EventLog("Application");
var tenMostRecentEvents = eventLog.Entries
.Cast<EventLogEntry>()
.Reverse()
.Take(10);
foreach (EventLogEntry entry in tenMostRecentEvents)
{
eventLogText.AppendLine(String.Format("{0} - {1}: {2}",
entry.Source,
entry.TimeWritten,
entry.Message));
}
Console.WriteLine(eventLogText.ToString());
}
catch (System.Security.SecurityException ex)
{
Console.WriteLine(ex);
}
Console.ReadLine();
}
Regarding your second question, your code will need the appropriate permissions to read that event log. For example, if I change the code read the Security event log using this line var eventLog = new EventLog("Security"); I will receive a security exception. You can check this answer for more information
Hope it helps!

C# SAPI in a web service

var speechEngine = new SpVoiceClass();
SetVoice(speechEngine, job.Voice);
var fileMode = SpeechStreamFileMode.SSFMCreateForWrite;
var fileStream = new SpFileStream();
try
{
fileStream.Open(filePath, fileMode, false);
speechEngine.AudioOutputStream = fileStream;
speechEngine.Speak(job.Script, SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak | SpeechVoiceSpeakFlags.SVSFDefault); //TODO: Change to XML
//Wait for 15 minutes only
speechEngine.WaitUntilDone((uint)new TimeSpan(0, 15, 0).TotalMilliseconds);
}
finally
{
fileStream.Close();
}
This exact code works in a WinForm app, but when I run it inside a webservice I get the following
System.Runtime.InteropServices.COMException was unhandled
Message="Exception from HRESULT: 0x80045003"
Source="Interop.SpeechLib"
ErrorCode=-2147201021
Does anyone have any ideas what might be causing this error? The error code means
SPERR_UNSUPPORTED_FORMAT
For completeness here is the SetVoice method
void SetVoice(SpVoiceClass speechEngine, string voiceName)
{
var voices = speechEngine.GetVoices(null, null);
for (int index = 0; index < voices.Count; index++)
{
var currentToken = (SpObjectToken)voices.Item(index);
if (currentToken.GetDescription(0) == voiceName)
{
speechEngine.SetVoice((ISpObjectToken)currentToken);
return;
}
}
throw new Exception("Voice not found: " + voiceName);
}
I have given full access to USERS on the folder C:\Temp where the file is to be written. Any help would be appreciated!
I don't think the System.Speech works in windows service. It looks like there is a dependency to Shell, which isn't available to services. Try interop with SAPI's C++ interfaces. Some class in System.Runtime.InteropServices may help on that.
Our naming convention requires us to use a non-standard file extension. This works fine in a Winforms app, but failed on our web server. Changing the file extension back to .wav solved this error for us.
Make sure you explicitly set the format on the SPFileStream object. ISpAudio::SetState (which gets called in a lower layer from speechEngine.Speak) will return SPERR_UNSUPPORTED_FORMAT if the format isn't supported.
I just got the webservice to spawn a console app to do the processing. PITA :-)

Categories

Resources