StreamWriter generates 0 byte file - c#

I have the following logics below that get called once every 20 minutes via a Timer, it serializes the content of the object into a file path, The filePath i see is \hard disk\logs\applicationstate.xml , please note I confirm this is a valid path..
It works most of the time but every now and then I get the System.IO.IOeException on the line this.StreamWriter = new StreamWriter(filePath); with the following stack stack trace:
at System.IO.__Error.WinIOError(Int32 errorCode, String str)\r\n at
System.IO.FileStream..ctor(String path, FileMode mode, FileAccess
access, FileShare share, Int32 bufferSize, Boolean useAsync, String
msgPath)\r\n at System.IO.FileStream..ctor(String path, FileMode
mode, FileAccess access, FileShare share, Int32 bufferSize)\r\n at
System.IO.StreamWriter.CreateFile(String path, Boolean append)\r\n
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding
encoding, Int32 bufferSize)\r\n at
System.IO.StreamWriter..ctor(String path)\r\n at
Shs.ScanPanel.CA.DataManager.DataManagercr.CopyData(Object data)\r\n
at System.Threading.Timer.ring()\r\n"
When it happens I see \hard disk\logs\applicationstate.xml exists but it has 0 byte.
So my question is, could the StreamWriter cause this 0 byte file to be generated in the first place? I read up on the IOException under StreamWriter on MSDN and it says the following
IOException
path includes an incorrect or invalid syntax for file name, directory name, or volume label syntax.
This confused me, is it because it tries to open a stream writer to a 0 byte file? could this 0 byte generated in the last time this code runs where a null object was being serialized into the file? if so why didn't I see that exception in Visual Studio?
if (filePath != string.Empty)
{
if (this.StateObject == null)
{
this.StateObject = new State();
}
//Do something to my StateObject object
this.StreamWriter = new StreamWriter(filePath);
this.Serializer = new XmlSerializer(typeof(State));
this.Serializer.Serialize(this.StreamWriter, this.StateObject);
}
else
{
if (this.log != null)
{
this.log.Write(LogLevel.Error, this.componentName, "CopyData : Unable to initilize State Object");
}
}
}
else
{
if (this.log != null)
{
this.log.Write(LogLevel.Error, this.componentName, "CopyData : Error while retrieving Current working directory");
}
}
}
catch (Exception ex)
{
if (this.log != null)
{
this.log.Write(ex, this.componentName);
}
}
finally
{
if (this.StreamWriter != null)
{
this.StreamWriter.Close();
}
}

I recommend using this.StreamWriter.Flush() to make sure all the contents are written.
However you exception appears to be complaining that the path is incorrect.
Edit: Opps I missed the WinCE tag

So I wrote up a little program and I confirmed that the line that makes the file to have 0 byte is right at the this.StreamWriter = new StreamWriter(filePath);
But what really boggle my mind is that it successfully wipe out the file so that new data can be serialized into it but yet at the same time it throws exception. I'm thinking this is a lower layer of the StreamWriter api or it could be something with the flash drive.... after all I'm running this program on WINDOW CE

Related

debug FileNotFoundException in depth C#

I'm having issues with random FileNotFoundExceptions when i'm creating a FileStream. The filepath is correct, the file exist, still i get FileNotFoundException at random times. How can i debug this more in detail? I'm running a Windows Mobile 6 project and this is the exception:
System.IO.FileNotFoundException: Could not find file '\Program Files\xxx\xxx\xxx-11133.bin'.
at System.IO.__Error.WinIOError(Int32 errorCode, String str)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean useAsync, String msgPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
This is the method that throws the exception:
internal static FInstance ReadAndDecrypt(string key, string fiId)
{
FileInfo fileInfo = new FileInfo(FullFilePath(fiId));
FileStream fileStream = null;
CryptoStream cryptoStream = null;
GZipInputStream zipStream = null;
try
{
int time = Environment.TickCount;
fileStream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read);
var serializer = new XmlSerializer(typeof(FInstance));
var FInstance = (FInstance)serializer.Deserialize(fileStream);
return Instance;
}
catch (Exception e)
{
Log.Error(e);
return null;
}
finally
{
if (fileStream != null)
fileStream.Close();
}
}
I can't think of anything that could cause this, is there any way to debug this deeper?
Debugging this should be straightforward. Add the following into your code right before your try/catch block:
if((!fileInfo.Exists) && (Debugger.IsAttached))
{
Debugger.Break();
}
This will get you to the state where the file isn't there. You should be checking for existence before opening the file in your production code anyway to protect against things like the file being deleted or in use while you app is already running.

System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

Guys can some one tell me why i have such error ....
2013-08-11 18:44:28 - NPMessage: DEBUG: Dispatching a RPCStorageWriteUserFileMessage
2013-08-11 18:44:28 - RPCStorageWriteUserFileMessage: INFO: Got a request for writing 8192 bytes to file iw4.stat for user alhpons.
2013-08-11 18:44:28 - ProfileData: INFO: Handling profile update request for alhpons
2013-08-11 18:44:28 - ProfileData: ERROR: Exception: System.IO.IOException: The process cannot access the file 'D:\IW4M\NpServer\data\priv2\00\000\alhpons\iw4.stat' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at System.IO.File.ReadAllBytes(String path)
at NPx.ProfileData.Handle(UpdateRequest request)
at NPx.ProfileData.Run()
Edit:
i use my App on windows server 2008 and some files need to read / write permission for my application but i have such error so i need to fix that problem and my source is:
public override void Process(NPHandler client)
{
var fileName = Message.fileName;
var fileData = Message.fileData;
var npid = (long)Message.npid;
var fsFile = StorageUtils.GetFilename(fileName, npid);
_client = client;
_fileName = fileName;
_npid = npid;
if (!client.Authenticated)
{
ReplyWithError(1);
return;
}
if (client.NPID != (long)npid)
{
ReplyWithError(1);
return;
}
if (!Directory.Exists(Path.GetDirectoryName(fsFile)))
{
Directory.CreateDirectory(Path.GetDirectoryName(fsFile));
}
// are we allowed to write this type of file?
if (!_fileHooks.ContainsKey(fileName))
{
ReplyWithError(1);
return;
}
string backupFile = null;
int result = _fileHooks[fileName](fileData, fsFile, out backupFile);
if (result > 0)
{
ReplyWithError(result);
return;
}
Log.Info(string.Format("Got a request for writing {0} bytes to file {1} for user {2}.", fileData.Length, fileName, npid.ToString("X16")));
try
{
var stream = File.Open(fsFile, FileMode.Create, FileAccess.Write);
stream.BeginWrite(fileData, 0, fileData.Length, WriteCompleted, stream);
if (backupFile != null)
{
var backupStream = File.Open(backupFile, FileMode.Create, FileAccess.Write);
backupStream.BeginWrite(fileData, 0, fileData.Length, BackupWriteCompleted, backupStream);
}
}
catch (Exception ex)
{
Log.Error(ex.ToString());
ReplyWithError(2);
}
}
Yes, the very program that gives you this message may be the program that is locking the file. Make sure to practice good housekeeping by closing each data stream after it has been used.
var stream = File.Open(fsFile, FileMode.Create, FileAccess.Write);
Where do you close this stream again?
The process cannot access the file xxx because it is being used by another process.
The Microsoft programmer that wrote this message was a trust-hearty soul. He did not want to assume that you got it wrong. When you are debugging your code, that message should however have ended with "is being used by a process". It includes your own.
Also note that you made the same mistake with backupStream. Since you are already using File.ReadAllBytes() to read the file, you might just as well use File.WriteAllBytes() to write it. If you can't afford the delay then you'll need to ensure it is closed in the WriteCompeted callback method.
If you already do this, then consider that the file might actually be in use by another process. Which does happen.

RAD PDF Service Message Worker Thread Unknown Exception

I try to open My PDF through RadPdf control but i get rendering error . i check the event viewer and get the following data :
to fix the problem i have to create C:\WINDOWS\TEMP\RadPdfTemp\ and the admin every period of time empty the temp and this folder removed , i try to create this folder in my my web site with the required permissions but still get the same error !!!
this.rad_pdf.CreateDocument("Document Name", pdfData);
I get pdfData through :
private byte[] AddReportToResponse(LocalReport followsReport)
{
string mimeType;
string encoding;
string extension;
string[] streams = new string[100];
Warning[] warnings = new Warning[100];
byte[] pdfStream = followsReport.Render("PDF", "", out mimeType, out encoding, out extension, out streams, out warnings);
return pdfStream;
}
Event Type: Error
Event Source: RAD PDF
Event Category: None
Event ID: 0
Date: 4/21/2013
Time: 2:33:50 PM
User: N/A
Computer: -----
Description:
Event Category
-----------------
PdfService
Event Description
-----------------
RAD PDF Service Message Worker Thread Unknown Exception
Exception Type:
System.IO.DirectoryNotFoundException
Exception Message:
Could not find a part of the path 'C:\WINDOWS\TEMP\RadPdfTemp\p476.tmp'.
Exception Stack Trace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at System.IO.File.WriteAllBytes(String path, Byte[] bytes)
at #Ew.#Rw.#ix()
at #Ew.#Rw.#9w()
Event User
-----------------
NT AUTHORITY\SYSTEM
Event Version
-----------------
2.12.0.0
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
You should check if the temp folder exist otherwise create it before you open the PDF file. That will make sure the folder is there and no exception is thrown.
string tempDirectory = Path.Combine(Path.GetTempPath(), "RadPdfTemp");
if (!Directory.Exists(tempDirectory))
Directory.CreateDirectory(tempDirectory);
this.rad_pdf.CreateDocument("Document Name", pdfData);

Illegal characters in path when using StreamReader

I am having trouble with opening up a StreamReader object in C#. I always receive the exception Illegal characters in path. The only way I can get it to work is if I use the entire path name using the # symbol to not escape any \ characters in the file path. However, this doesn't really help me because I start with the two separate variables for the file's path and the file's name as output from another method (which can not be changed).
I've gone through eight permutations that all failed, which are commented out below for reference. For the sake of readability here, pretend I'm declaring dirIni and fileIni instead of receiving their values as output from another method. With that said, both declaration style 1 and 2 failed using all four concatenation methods. What is going on here? I've pretty much seen all four concatenation methods work in other examples.
EDIT:
I've simplified the code to show 1 version of what breaks for me:
string dirIni = #"C:\Users\Dan\AppData\Local\MyApp 4.0\INI\";
string fileIni = #"PWTRANSACTION.INI";
try
{
string transIniFullFileName = Path.Combine(dirIni, fileIni);
using (StreamReader file = new StreamReader(transIniFullFileName))
{
// do StreamReader stuff...
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Here is the exception's stack trace:
at System.IO.Path.CheckInvalidPathChars(String path)
at System.IO.Path.GetFileName(String path)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)
at System.IO.StreamReader..ctor(String path)
at TestApp.Form1.btnTestRead_Click(Object sender, EventArgs e) in C:\Users\Dan\TestApp\Form1.cs:line 4977
The issue was the method was returning a string which had a Field Separator character at the end, and that was the illegal character. I was also using these strings in my test code. I pasted my code into notepad++ and toggled on "Show Hidden Characters" and I could see the FS character then. After removing the FS, everything ran properly. Thank you all for helping me test the code, especially #Dynguss.
Any time VS gives the Illegal Character exception, check for potential hidden characters!
The following should work:
string dirIni = #"C:\Users\Dan\AppData\Local\MyApp 4.0\INI";
string fileIni = "PWTRANSACTION.INI";
string transIniFullFileName = Path.Combine(dirIni, fileIni);
and to avoid hardcoding the Local Application Data folder:
string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string dirIni = #"MyApp 4.0\INI";
string fileIni = "PWTRANSACTION.INI";
string transIniFullFileName = Path.Combine(localAppData, dirIni, fileIni);
By the way the following two string declarations are perfectly identical:
string transIniFullFileName = "C:\\Users\\Dan\\AppData\\Local\\MyApp 4.0\\INI\\PWTRANSACTION.INI";
string transIniFullFileName = #"C:\Users\Dan\AppData\Local\MyApp 4.0\INI\PWTRANSACTION.INI";
So if you are saying that the first fails but the second succeeds, well, I guess there's something else that's failing and you are not showing us your real code.
I had this same error and for me it was caused by using a string instead of a path in StreamReader
string[] blocks = content.Split(';');
foreach(string block in blocks)
{
StreamReader strReader = new StreamReader(block);
Debug.WriteLine(block);
}
I removed the StreamReader line and got what I wanted.
string[] blocks = content.Split(';');
foreach(string block in blocks)
{
Debug.WriteLine(block);
}

Exception: Access Denied when using FileStream

The following line is throwing an exception. I have no idea why.
using (var output = new FileStream(sftpFile.Name, FileMode.Create,FileAccess.ReadWrite))
Exception is:
Error: System.UnauthorizedAccessException: Access to the path 'C:\Users\roberth\
Programming_Projects\Common\UI\bin\Debug' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access,
Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions
options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy,
Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
at CWD.Networking.DownloadFromSftp(String hostname, String user, String passw
ord, Int32 port, String localPath, String remotePath, String filename) in c:\Use
rs\roberth\Programming_Projects\Common\Common\Common.cs:line 566
Line 566 is the using statement above.
Can anyone shed some light as to why I may be triggering an error? I have full permissions to the directory, no compilation issues, I can create new files and folders manually in that directory as well.
--Edit--
I tried running VS as administrator as suggested with no resolution.
The UnauthorizedAccessException error message tells you what file it is you're trying to open:
C:\Users\roberth\Programming_Projects\Common\UI\bin\Debug
This looks like a directory name: you can't open a directory as a file.
You've presumably forgotten to append a filename:
string filename = Path.Combine(sftpFile.Name, "SomeFile.dat");
using (var output = new FileStream(filename,...)
{
...
}
You need to use something similar to the following:
private bool EnviarArchivoSFTP(string PuertoSFTP, string UrlFTP, string CarpetaFTP, string UsuarioFTP, string PasswordFTP, string FicheroFTP, string nombreArchivo)
{
bool archivoEnviado = false;
using (var client = new SftpClient(UrlFTP, int.Parse(PuertoSFTP), UsuarioFTP, PasswordFTP))
{
client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(1);
client.OperationTimeout = TimeSpan.FromSeconds(1);
client.Connect();
client.ChangeDirectory(CarpetaFTP);
string dataPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string appFile = Path.Combine(dataPath, FicheroFTP, nombreArchivo);//Se brindan permisos full sobre la carpeta
using (var fileStream = new FileStream(appFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
client.BufferSize = 4 * 1024; // bypass Payload error large files
client.UploadFile(fileStream, Path.GetFileName(nombreArchivo));
archivoEnviado = true;
}
}
return archivoEnviado;
}

Categories

Resources