other process is still using this file - c#

public void button1_Click(object sender, EventArgs e)
{
//string item = ofd.FileName;
ofd.InitialDirectory = "c:\\";
ofd.Filter = "exe files (*.exe)|*.exe";
ofd.Multiselect = true;
ofd.RestoreDirectory = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
listBox1.Items.Clear();
string tmp = Path.Combine(Path.GetDirectoryName(listBox2.GetItemText(listBox2.Items)), "\\inputdata.txt");
File.Create(tmp);
using (File.Open(tmp, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
;
foreach (string item in ofd.FileNames)
{
string date = Path.GetFileName(item.Substring(10, 16));
string ite = item.Substring(0, item.IndexOf(".h2"));
listBox1.Items.Add(item);
if (File.ReadAllText(tmp).Contains(Path.GetFileName(item).Substring(10, 16)))
{
File.AppendAllText(tmp, Environment.NewLine);
}
if (item.IndexOf("MOD10A") >= 0)
{
if (File.ReadAllText(tmp).IndexOf(date) < 0)
{
File.AppendAllText(tmp, ite.Replace("MOD10A1.A", "ter_"));
}
}//
if (item.IndexOf("MYD10A") >= 0)
{
if (File.ReadAllText(tmp).IndexOf(date) < 0)
{
File.AppendAllText(tmp, ite.Replace("MYD10A1.A", "Aqu_"));
}
}
File.AppendAllText(tmp, ", " + item);
}
}
}
}
listbox2 has filename which i get from openfiledialog. like C:\Program Files (x86)\Microsoft\file.exe
when i debug this program. error happens. message is that The process cannot access the "c:\inputdata.txt" because it is being used by another process.
I don't understand why inputdata.txt is located in c:\ and why error is happening.
What is the reason for this error?

You must close the FileStream after use it.
Look at this :
Closing a file after File.Create
https://msdn.microsoft.com/en-us/library/aa328800(v=vs.71).aspx

First read the text file then after update the file.
using (File.Open(tmp, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
/// Not right here a append txt logic
}
// Code File.AppendAllText
Then after right here appned or update logic here.bcz, If file is already open you can't write or update the file.

Related

C# - I'm having problems overwriting data in text file from Listbox

I'm creating a small program that can save website urls/links into a listbox. From there, I can save the contents of the listbox onto a text file. That text file is then saved to a folder on my desktop that was prematurely made for the program. The application can open a text file and display the contents to the listbox as well as create and save a new text file with. My problem is how would I overwrite the text file properly.
This is the code I have for the Save Toolbox button:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
string line = "";
if (File.Exists(path)) //the path string is a folder on my desktop
{
FileStream fstream = File.Open(path, FileMode.Create);
while (line != null)
{
using (StreamWriter write = new StreamWriter(fstream))
{
foreach (object item in WebListBox.Items)
write.WriteLine(item.ToString());
}
}
}
else
{
saveFileDialog1.Filter = "Text files (*.txt)|*.txt";
saveFileDialog1.Title = "Save as Text File";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (FileStream S = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
{
using (StreamWriter st = new StreamWriter(S))
{
foreach (var items in WebListBox.Items)
st.WriteLine(items.ToString());
}
}
}
}
}
The problem is that after I create the text file using the Save As ToolBar button, the compiler seemingly ignores the code in my if statement and assumes that I want to always create a new text file to save to. Thanks in advance!
After multiple revisions and outside help, I figured out the problem. The file name I was trying to retrieve from my folder directory was null, so nothing would be saved. Therefore what I did was I would retrieve the file name from the form itself if it was last opened/saved onto the form.
Here's a picture to help visualize. Any text file that was last opened or saved, it would display it here and compiler would use that path in my code.
Using the full path of the file instead of the shorten one, I would overwrite the contents of the file to that path. Doing this also allows me save my files anywhere on my computer.
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
var fileNameAndPath = filedisplaylabel.Text;
if (string.IsNullOrEmpty((fileNameAndPath)))
{
OpenFileDialog openfiledialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
filedisplaylabel.Text = Path.GetFullPath(openFileDialog1.FileName);
fileNameAndPath = filedisplaylabel.Text;
}
}
try
{
using (FileStream fstream = new FileStream(fileNameAndPath,
FileMode.Open,
FileAccess.Write))
{
using (StreamWriter write = new StreamWriter(fstream))
{
foreach (var item in WebListBox.Items)
write.WriteLine(item.ToString());
write.Close();
}
fstream.Close();
}
}
catch (DirectoryNotFoundException ex)
{
MessageBox.Show(ex.Message, "File not found error");
}
}

DataGridView and copy image

I met one problem when I tried to copy file.
Error description
I worked with DataGridView and PictureBox.
Deguber of VS 2015 stopped me at
FileStream fs = File.Open(file, FileMode.Open);
in function CopyFile. I cant understand what's wrong i did.
This is some code (C#, .NET 4.5.1) from main form:
static string CopyFile(string file, string to)
{
FileInfo fileInfo = new FileInfo(file);
byte tmp = 0;
string temp = to + "\\" + fileInfo.Name;
FileStream newFile = File.Open(temp, FileMode.Create);
try
{
FileStream fs = File.Open(file, FileMode.Open);
for (int i = 0; i < fileInfo.Length; i++)
{
tmp = (byte)fs.ReadByte();
newFile.WriteByte(tmp);
}
fs.Close();
}
catch (FileNotFoundException ex)
{
MessageBox.Show("Не вдалося найти файл.");
}
newFile.Close();
return temp;
}
private void WriteNewUserToFile(User item, string pathToFile)
{
StreamWriter sw = new StreamWriter(File.Open(#pathToFile, FileMode.Append, FileAccess.Write));
sw.WriteLine(string.Format("{0}, {1}, {2}, {3}, {4}, {5}",
item.Id,
item.Image,
item.FirstName,
item.LastName,
item.Email,
item.Phone));
sw.Close();
}
private void btnAddUser_Click(object sender, EventArgs e)
{
AddUserForm dlg = new AddUserForm();
if (dlg.ShowDialog() == DialogResult.OK)
{
User item = dlg.NewUser;
item.Image = CopyFile(item.Image, "images");
WriteNewUserToFile(item, "data/users.dat");
users.Add(item);
//this.AddNewDataGridRow(item);
}
}
And some code of AddNewUserForm:
public User NewUser
{
get { return newUser; }
set { newUser = value; }
}
private void btnImage_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
txtImage.Text = dlg.FileName;
try
{
picboxImage.Image = Image.FromFile(txtImage.Text);
}
catch
{
picboxImage.Image = Image.FromFile(#"images\NoImg.bmp");
}
}
}
private void btnApply_Click(object sender, EventArgs e)
{
NewUser = new User
{
Id = Convert.ToInt32(txtId.Text),
LastName = txtLastName.Text,
FirstName = txtFirstName.Text,
Email = txtEmail.Text,
Phone = txtPhone.Text,
Image = txtImage.Text
};
this.DialogResult = DialogResult.OK;
}
If somebody need all project/code, click here (download VS project).
When you set the Image for the PictureBox using the following code, the call keeps the file handle open. So when you try to open the file again you encounter the exception.
picboxImage.Image = Image.FromFile(txtImage.Text);
According to this accepted answer, when the file handle is closed is unpredictable, in some cases, the handle won't be closed even if you explicitly close the Image.
So you may use the technique in that answer like this, to ensure the file handle is closed properly.
picboxImage.Image = Image.FromStream(new MemoryStream(File.ReadAllBytes(txtImage.Text)));

openfiledialog results in file is being used by another process [duplicate]

This question already has an answer here:
System.IO.IOException: 'The process cannot access the file because it is being used by another process
(1 answer)
Closed 2 years ago.
I would like use C# to upload multiple files to google drive
this is my upload button function
private void bt_upload_Click(object sender, EventArgs e)
{
Filedialog_init();
DialogResult check_upload = MessageBox.Show("Want to upload these files ?", "Upload", MessageBoxButtons.OKCancel);
if (check_upload == DialogResult.OK)
{
for (int i = 0; i < result.Count; i++)
{
UploadFilesDrive(service, result[i], filePath[i], Datatype[i]);
tx_state.AppendText(result[i] + "Upload Done");
}
}
}
This is my Filedialog_init function
private static void Filedialog_init()
{
Stream myStream = null;
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "bin files (*.bin)|*.bin|All files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
openFileDialog.Multiselect = false;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string filename = null;
string _datatype = null;
try
{
if ((myStream = openFileDialog.OpenFile()) != null)
{
foreach (String file in openFileDialog.FileNames)
{
filename = Path.GetFileName(file);
result.Add(filename);
// only show the name of file
Datatype.Add(_datatype);
}
filePath = openFileDialog.FileNames;
Datatype.ForEach(Console.WriteLine);
}
openFileDialog.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
else
MessageBox.Show("Upload Cancel");
}
I can upload the file successfully by assigning the filename and its datatype and path directly
But when I used openfiledialog,it went wrong with "my file is being used by another process"
How can I solve this problem?
Issue lies in your code here,
(myStream = openFileDialog.OpenFile()) This line is keeping lock on the file because your myStream does not get disposed. you need to dispose the stream as soon as you are done with it.
So try with using as it will dispose the stream as soon as your end using line gets executed. More details on using.
you can try as below,
using(Stream myStream = openFileDialog.OpenFile())
{
//Your code here...
}

display file instead of RSC version

Whenever I try to open a custom file to a textbox or something which will display code. it never works, I'm not sure what I am doing wrong.
I want my program to display what is inside the file when I open it, I have this below:
private void button1_Click(object sender, EventArgs e)
{
//Show Dialogue and get result
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "rbt files (*.rbt)|*.rbt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
File.WriteAllText("", CodeBox.Text);
}
}
}
catch (Exception ex)
{
MessageBox.Show("RBT7 file open");
}
}
}
It only displays the RBT7 in a messagebox which is not what I want, I want the file to open and display its information to some sort of textbox which displays code.
Please read the documentation for File.WriteAllText.
The first parameter:
path: The file to write to.
You're passing it "". That is not a path. Are you trying to write all the text from the file into CodeBox.Text or write all the text from CodeBox.Text into a file?
In your comment, you indicate the former. Try this:
string[] lines = System.IO.File.ReadAllLines(#"your file path");
foreach (string line in lines)
{
CodeBox.Text += line;
}
You haven't shown the code for CodeBox so I can't guarantee the results of this.
Try this:
Replace this code
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
File.WriteAllText("", CodeBox.Text);
}
}
with this
{
CodeBox.Text = File.ReadAllText(openFileDialog1.FileName);
}

C# File - Read files from desktop and write them to a specific file

I created a System.Timers.Timer object with an interval of 5000 ms. On the Elapsed event of this timer, I'm searching the new PDF files which appeared on Desktop. If there are new PDF files, I add those to the specific file, but my program catch this error: The process cannot acces the file 'C:\Users\Admin\Desktop\StartupFiles.dat' because it is being used by another process.
Here is my code:
private readonly string fileName = Application.StartupPath + #"\StartupFiles.dat";
private readonly string sourceDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
void timerCheck_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
if (!File.Exists(fileName))
File.Create(fileName);
string[] PDFiles = Directory.GetFiles(sourceDirectory, "*.pdf", SearchOption.TopDirectoryOnly);
string[] textFile = File.ReadAllLines(fileName);
bool exist;
string addText = string.Empty;
foreach (string s in PDFiles) // Check the files from the desktop with the files from the fileName variabile folder
{
exist = false;
foreach (string c in textFile)
{
if (string.Compare(s, c) == 0)
{
exist = true;
break;
}
}
if (!exist)
{
addText += s + '\n';
}
}
if (!string.IsNullOrEmpty(addText)) // If a new PDF appeard on the desktop, save it to file
{
using (StreamWriter sw = File.AppendText(fileName))
{
sw.Write(addText);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Maybe I have to set a little delay between ReadAllLines and File.AppendText ?
#charqus, This should Work
if (!File.Exists(fileName))
File.Create(fileName).Dispose();
string[] PDFiles = Directory.GetFiles(sourceDirectory, "*.pdf", SearchOption.TopDirectoryOnly);
List<String> fileList = new List<String>();
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
using (BinaryReader r = new BinaryReader(fs))
{
fileList.Add(r.ReadString());
}
}
string[] textFile = fileList.ToArray();
Calling the Dispose method ensures that all the resources are properly released.

Categories

Resources