System.IO.IOException being used by another process - c#

I am trying to write to a file, I believe i am closing the file that i had read in earlier in the code, but I am getting a "System.IO.IO.Exception" This is my code for reading and writing to the file.
public class InOutTxt
{
public List<Employee> ReadFile(string fileName) {
FileStream fs = new FileStream(fileName,FileMode.Open ,FileAccess.ReadWrite);
StreamReader fileIn = new StreamReader(fileName);
fileIn = File.OpenText(fileName);
List<Employee> list = new List<Employee>();
string[] test;
string name;
string ID;
string dep;
string post;
while (!fileIn.EndOfStream || !File.Exists(fileName)) {
string inString = fileIn.ReadLine();
test = inString.Split('#');
name = test[0];
ID = test[1];
dep = test[2];
post = test[3];
Employee newEmp = new Employee(name, ID, dep, post);
list.Add(newEmp);
}
fileIn.Close();
fs.Close();
return list;
}
public void WriteFile(List<Employee> outList, string file) {
FileStream fs = new FileStream(file, FileMode.Open, FileAccess.ReadWrite);
StreamWriter writeOut = new StreamWriter(file);
for (int i = 0; i < outList.Count; i++) {
writeOut.WriteLine(outList[i].name + '#' + outList[i].IDnum + '#' + outList[i].department + '#' + outList[i].position);
}
writeOut.Close();
fs.Close();
}
}
The Error is occuring at this part of the code
StreamReader fileIn = new StreamReader(fileName);
If it helps any it was running well earlier today, the only major change I have made was the addition of the FileStream attribute above.

System.IO.IOException being used by another process
You have opened file using the FileStream constructor and the StreamReader gives error when it tries to open the file again using the fileName constructor. Pass the FileStream object instead of fileName.
FileStream Constructor (String, FileMode)
The constructor is given read/write access to the file, and it is
opened sharing Read access (that is, requests to open the file for
writing by this or another process will fail until the FileStream
object has been closed, but read attempts will succeed), MSDN.
//File is opened by FileStream and not available for opening before it is closed.
FileStream fs = new FileStream(fileName,FileMode.Open ,FileAccess.ReadWrite);
StreamReader fileIn = new StreamReader(fs); //Here pass fs instead of fileName

Related

In C# Dot Net, How to handle a exception when you want to de-serialize a xml file?, but by default the file doesn't exists

In C# Dot Net, How to handle a exception when you want to de-serialize a xml file, but by default the file doesn't exists! because you have to run the program to create one.
Below is the area where I need Help.
public static Compare_Data[] Deserialize()
{
Compare_Data[] cm;
cm = null;
string path = #"C:\Users\XYZ\Desktop\BACKUP_DATA\log.xml";
XmlSerializer xs = new XmlSerializer(typeof(Compare_Data[]));
if (File.Exists(path))
{
using (FileStream fs = new FileStream(path, FileMode.Open))
{
// This will read the XML from the file and create the new instance of Compare_Data.
cm = (Compare_Data[])xs.Deserialize(fs);
return cm;
}
}
else
{
using (FileStream fs = new FileStream(path, FileMode.Create))
{
xs.Serialize(fs); /// what to add here ?
}
}
return null;
}
If general, you don't want your methods to have side effects. In this case, creating an empty log file in the else branch is probably unnecessary and should be handled by a separate Serialize() method when there is data to be logged.
Your code could be simplified something like this:
public static Compare_Data[] Deserialize()
{
const string path = #"C:\Users\XYZ\Desktop\BACKUP_DATA\log.xml";
if (!File.Exists(path))
{
// return null or an empty array, depending on how
// you want the calling code to handle this.
return null;
}
using (FileStream fs = new FileStream(path, FileMode.Open))
{
var xs = new XmlSerializer(typeof(Compare_Data[]));
return (Compare_Data[])xs.Deserialize(fs);
}
}

uploading a file using WCF in ASP.NET

I have created one WCF service that will upload the file. and after using that service I am trying to upload the file I am able to successfully upload the file but there is some issue with the FILESTREAM class.
The moment i clicked the button to upload the file when i checked by debugging the application i get to know that stream object is null.
I am passing the object of stream class to the WCF method.
But due to some issue that stream object is getting null.
due to that null object of stream class, image which is uploded getting empty in my folder
This is my code that I am using to upload the file
if (FileUpload1.HasFile)
{
System.IO.FileInfo fileInfo = new System.IO.FileInfo(FileUpload1.PostedFile.FileName);
FileTransferServiceReference.ITransferService clientUpload = new FileTransferServiceReference.TransferServiceClient("BasicHttpBinding_ITransferService");
FileTransferServiceReference.RemoteFileInfo uploadRequestInfo = new RemoteFileInfo();
string Path = System.IO.Path.GetDirectoryName(FileUpload1.FileName);
using (System.IO.FileStream stream = new System.IO.FileStream(FileUpload1.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
uploadRequestInfo.FileName = FileUpload1.FileName;
uploadRequestInfo.Length = fileInfo.Length;
uploadRequestInfo.FileByteStream = stream;
clientUpload.UploadFile(uploadRequestInfo);
}
}
Code for WCF Service
public RemoteFileInfo DownloadFile(DownloadRequest request)
{
RemoteFileInfo result = new RemoteFileInfo();
try
{
// get some info about the input file
string filePath = System.IO.Path.Combine(#"c:\Uploadfiles", request.FileName);
System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
// check if exists
if (!fileInfo.Exists) throw new System.IO.FileNotFoundException("File not found", request.FileName);
// open stream
System.IO.FileStream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
// return result
result.FileName = request.FileName;
result.Length = fileInfo.Length;
result.FileByteStream = stream;
}
catch (Exception ex)
{
}
return result;
}
public void UploadFile(RemoteFileInfo request)
{
FileStream targetStream = null;
Stream sourceStream = request.FileByteStream;
string uploadFolder = #"C:\upload\";
if (!Directory.Exists(uploadFolder))
{
Directory.CreateDirectory(uploadFolder);
}
string filePath = Path.Combine(uploadFolder, request.FileName);
using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
const int bufferLen = 65000;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
{
targetStream.Write(buffer, 0, count);
}
targetStream.Close();
sourceStream.Close();
}
}
}
Spot the difference:
string uploadFolder = #"C:\upload\";
...
string filePath = System.IO.Path.Combine(#"c:\Uploadfiles", request.FileName);
As a general tip you might put your upload file path into an external configuration file, so that you can change it when you move your application onto a server where you need to store the data on a different drive or in a specific location.
Also that way you are always calling the same configuration entry so your upload path name is definitely going to be the same everywhere.

Storing more than one value into Isolated Storage

I have created a isolated storage that only store one values and display one value of e.g. "aaaaaaaa,aaaaaaaa".
How can I make it so that it stores
1)"aaaaaaaa,aaaaaaaaa"
2)"bbbbbbbb,bbbbbbbbb"
3)"cccccccccc,cccccccccc"
Below shows codes that stores only one value:
//get the storage for your app
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
//define a StreamWriter
StreamWriter writeFile;
if (!store.DirectoryExists("SaveFolder"))
{
//Create a directory folder
store.CreateDirectory("SaveFolder");
//Create a new file and use a StreamWriter to the store a new file in
//the directory we just created
writeFile = new StreamWriter(new IsolatedStorageFileStream(
"SaveFolder\\SavedFile.txt",
FileMode.CreateNew,
store));
}
else
{
//Create a new file and use a StreamWriter to the store a new file in
//the directory we just created
writeFile = new StreamWriter(new IsolatedStorageFileStream(
"SaveFolder\\SavedFile.txt",
FileMode.Append,
store));
}
StringWriter str = new StringWriter();
str.Write(textBox1.Text);
str.Write(",");
str.Write(textBox2.Text);
writeFile.WriteLine(str.ToString());
writeFile.Close();
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
StringWriter str = new StringWriter();
str.Write(textBox1.Text);
str.Write(",");
str.Write(textBox2.Text);
writeFile.WriteLine(str.ToString());
writeFile.Close();
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
You can use WriteLine several times like below
writeFile.WriteLine(string.Format("{0},{1}", "aaaaa","aaaaa"));
writeFile.WriteLine(string.Format("{0},{1}", "bbbbb","bbbbb"));
writeFile.WriteLine(string.Format("{0},{1}", "ccccc","ccccc"));
I can confirm Damith's answer, and should be marked as so.
If you're wondering about reading the lines back in:
IsolatedStorageFileStream stream = new IsolatedStorageFileStream("SaveFolder", FileMode.Open, store);
StreamReader reader = new StreamReader(stream);
string rdr = reader.ReadLine();
rdr will be a string representing the first line, you can then call ReadLine() again to get the next line, etc. The first call to ReadLine() will return the first line you wrote to the store.
Hope this is useful to you or anyone else working in this area.

Read log file being used by another process

Goal
I want to press a button on my GUI and read in the seclog.log file (symantec AV log) from a remote machine and display the contents of the log to a rich text box in my application.
Things That Work
everything but reading the log file
Error Message
System.IO.IOException was unhandled
Message=The process cannot access the file '\\HOSTNAME\C$\Program Files (x86)\Symantec\Symantec Endpoint Protection\seclog.log' because it is being used by another process.
Source=mscorlib
code
//possible seclog paths
String seclogPath1 = #"\\\\" + target + "\\C$\\Program Files (x86)\\Symantec\\Symantec Endpoint Protection\\seclog.log";
String seclogPath2 = #"\\\\" + target + "\\C$\\Program Files\\Symantec\\Symantec Endpoint Protection\\seclog.log";
//if seclog exists
if (File.Exists(seclogPath1))
{
//output.AppendText("file exists at " + seclogPath1);
//var seclogContent = File.Open(seclogPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Stream stream = File.OpenRead(seclogPath1);
StreamReader streamReader = new StreamReader(stream);
string str = streamReader.ReadToEnd();
output.AppendText(str);
streamReader.Close();
stream.Close();
}
Things I've Tried
File is being used by another process
C# The process cannot access the file ''' because it is being used by another process
Googling the issue
using filestreams in multiple ways
//possible seclog paths
String seclogPath1 = #"\\\\" + target + "\\C$\\Program Files (x86)\\Symantec\\Symantec Endpoint Protection\\seclog.log";
String seclogPath2 = #"\\\\" + target + "\\C$\\Program Files\\Symantec\\Symantec Endpoint Protection\\seclog.log";
//if seclog exists
if (File.Exists(seclogPath1))
{
//output.AppendText("file exists at " + seclogPath1);
//var seclogContent = File.Open(seclogPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Stream stream = File.Open(seclogPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//File.OpenRead(seclogPath1);
StreamReader streamReader = new StreamReader(stream);
string str = streamReader.ReadToEnd();
output.AppendText(str);
streamReader.Close();
stream.Close();
}
what i had to change
i had to create a readwrite filestream
original code
Stream stream = File.OpenRead(seclogPath1);
StreamReader streamReader = new StreamReader(stream);
new code
Stream stream = File.Open(seclogPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//File.OpenRead(seclogPath1);
StreamReader streamReader = new StreamReader(stream);
using (StreamReader sr = new StreamReader(filePath, true))
{
sr.Close(); //This is mandatory
//Do your file operation
}

IsolatedStorage ArgumentNullException

I don't see what's the matter here:
Constructor:
IsolatedStorageFile isf;
public FileManagement()
{
isf = IsolatedStorageFile.GetUserStoreForApplication();
}
when I save files:
public bool saveCredentials(String username, String userpass)
{
bool res = false;
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("usercred.custom",
FileMode.Create, FileAccess.Write, isf));
writeFile.WriteLine(username);
writeFile.WriteLine(userpass);
res = true;
return res;
}
and when I try to read them:
public String readUsername()
{
String username = "";
IsolatedStorageFileStream fileStream = isf.OpenFile("usercred.custom", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(fileStream);
username = reader.ReadLine();
return username;
}
Reading returns null.
I try to save a file and write something into it, but it somehow doesn't work.
You have to close your streams. Please add reader.Close(), writefile.Close() and fileStream.Close() before return and try again.

Categories