Error while accessing file C# - c#

I get the Error (IOException) that I don't know where is the error. Here he code:
The constructor:
private const int MAX = 200;
private String path = "\\Registros\\reg";
private FileStream fs;
private BinaryWriter bw = null;
private BinaryReader br = null;
private int N;
private long pos;
public Manejo_Ficheros(String filepath){
this.path = filepath;
if(!File.Exists(path+".dat")){
fs = new FileStream(path + ".dat", FileMode.Create);
this.N = 0;
bw = new BinaryWriter(fs);
fs.Seek(0,SeekOrigin.Begin);
bw.Write(N);
}else{
fs = new FileStream(path + ".dat", FileMode.Open);
br = new BinaryReader(fs);
fs.Seek(0,SeekOrigin.Begin);
this.N = br.ReadInt32();
}
}
Here the Writting:
public void escribirRegistro(Persona p)
{
pos = 4 + this.N * MAX;
int i = (int)pos;
bw = new BinaryWriter(fs);
bw.Seek(i, SeekOrigin.Begin);
bw.Write(p.ID);
bw.Write(p.nombre);
bw.Write(p.apellidos);
bw.Write(p.Num);
bw.Write(p.Nced);
bw.Write(p.pais);
bw.Write(p.observaciones);
bw.Write(p.Anac);
bw.Write(p.tPer);
this.N += 1;
fs.Seek(0, SeekOrigin.Begin);
bw.Write(N);
bw.Close();
fs.Close();
}
As you can see, I am using a flush. It will receive a "Persona" object type and then Writting to a File.
The writting is working fine. But when I want to use the reading method see:
public Persona[] leerTodos()
{
Persona[] p = new Persona[this.N];
br = new BinaryReader(fs);
for (int i = 0; i < p.Length; i++)
{
pos = 4+i*MAX;
br.BaseStream.Seek(pos, SeekOrigin.Begin);
Persona p1 = new Persona();
p1.ID = br.ReadInt32();
p1.nombre = br.ReadString();
p1.apellidos = br.ReadString();
p1.Num = br.ReadString();
p1.Nced = br.ReadString();
p1.pais = br.ReadString();
p1.observaciones = br.ReadString();
p1.Anac = br.ReadInt32();
p1.tPer = br.ReadString();
p[i] = p1;
}
return p;
}
The application breaks in this line fs = new FileStream(path + ".dat", FileMode.Open); The process cannot access the file 'C:\Users\Allan\Desktop\data.dat' because it is being used by another process.
Thing that Writting it does not happen. I dont know what is going wrong.

Try doing this in your code
public Manejo_Ficheros(String filepath){
this.path = filepath;
if(!File.Exists(path+".dat")){
using (fs = new FileStream(path + ".dat", FileMode.Create));
{
this.N = 0;
bw = new BinaryWriter(fs);
fs.Seek(0,SeekOrigin.Begin);
bw.Write(N);
}
}else{
using (fs = new FileStream(path + ".dat", FileMode.Open))
{
br = new BinaryReader(fs);
fs.Seek(0,SeekOrigin.Begin);
this.N = br.ReadInt32();
}
}

Related

Upload file multipartformdata to Hubspot api

I'm trying to upload files to the hubspot api.
https://developers.hubspot.com/docs/methods/files/post_files
Everything looks ok when I look in the CRM except that some filenames looks wierd.
The files get created and get a filesize but seams corrupt cause I can't open them or download them.
My method looks like this
private async Task<HsCreateFileResponse> UploadAttachment(string pStream, string pFilename)
{
string url = API_BASE_URL + "filemanager/api/v2/files?hapikey=" + API_KEY;
string path = #"C:\Temp filer\";
HttpClient client = new HttpClient();
var content = new MultipartFormDataContent();
content.Headers.Add("hidden", "true");
using (var s = new MemoryStream())
{
using (var writer = new StreamWriter(s))
{
writer.Write(pStream);
s.Position = 0;
using (var fs = new FileStream(path + pFilename, FileMode.Create))
{
s.CopyTo(fs);
}
writer.Flush();
}
}
using (var fs = new FileStream(path + pFilename, FileMode.Open, FileAccess.Read))
{
byte[] bytes = new byte[fs.Length];
int numBytesToRead = (int)fs.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
int n = fs.Read(bytes, numBytesRead, numBytesToRead);
if (n == 0)
{
break;
}
numBytesRead += n;
numBytesToRead -= n;
}
numBytesToRead = bytes.Length;
System.Threading.Thread.Sleep(100);
content.Add(new StreamContent(new MemoryStream(bytes)), "files", pFilename);
var res = await client.PostAsync(url, content);
return JsonConvert.DeserializeObject<HsCreateFileResponse>(await res.Content.ReadAsStringAsync());
}
}
Add this to the content:
content.Add(new StringContent("my-folder/and-subfolder"), "folder_paths");
content.Add(new StringContent("my-file-name.png"), "file_names");

C# data extracting from the file into byte array

Can anyone explain me about the following code what it is doing and
why it is substracting the size by 44.
public byte[] recorded_file = new byte[1000000];
public bool recorded_first_stream;
public int recorded_file_location;
public async void TestFile(object object_name)
{
string file_name = (string)object_name;
string full_file_name = System.IO.Path.Combine
(Properties.Settings.Default.wave_files_location, file_name);
if (File.Exists(full_file_name))
{
// WaveStream fileStream = new AudioFileReader(full_file_name);
recorded_first_stream = true;
FileStream fs = File.Open(full_file_name, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite);
recorded_file_location = (int)new System.IO.FileInfo(full_file_name).Length - 44;
BinaryReader wave_file = new BinaryReader(fs);
wave_file.BaseStream.Seek(44, SeekOrigin.Begin);
byte[] wave_bytes = wave_file.ReadBytes(1000000);
Buffer.BlockCopy(wave_bytes, 0, recorded_file, 0, wave_bytes.Length);
}

How do I check if a file is a SQLite Database in C#?

SQLiteConnection.Open does not throw exception when opening a file that is not a database.
private void openDatabase()
{
sqlite = new SQLiteConnection("Data Source=" + this.filePath + ";Version=3;");
try
{
sqlite.Open();
}
catch(SQLiteException e)
{
MessageBox.Show(e.Message + e.StackTrace);
}
}
How do I determine if a file is a SQLite Database?
Read the first 16 bytes and then check for the string "SQLite Format"
VB.Net
Dim bytes(16) As Byte
Using fs As New IO.FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
fs.Read(bytes, 0, 16)
End Using
Dim chkStr As String = System.Text.ASCIIEncoding.ASCII.GetString(bytes)
Return chkStr.Contains("SQLite format")
Update 2
C#
byte[] bytes = new byte[17];
using (IO.FileStream fs = new IO.FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
fs.Read(bytes, 0, 16);
}
string chkStr = System.Text.ASCIIEncoding.ASCII.GetString(bytes);
return chkStr.Contains("SQLite format");
public static bool isSQLiteDatabase(string pathToFile)
{
bool result = false;
if (File.Exists(pathToFile)) {
using (FileStream stream = new FileStream(pathToFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
byte[] header = new byte[16];
for (int i = 0; i < 16; i++)
{
header[i] = (byte)stream.ReadByte();
}
result = System.Text.Encoding.UTF8.GetString(header).Contains("SQLite format 3");
stream.Close();
}
}
return result;
}

File Input/output issue

int AccNum;
FileStream myfile = new FileStream("C:\\bankin.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamReader rd = new StreamReader(myfile);
StreamWriter wt = new StreamWriter(myfile);
int a = Convert.ToInt32(rd.ReadLine());
AccNum = a;
a += 1;
wt.WriteLine(Convert.ToString(a));
Console.WriteLine(rd.ReadLine());
rd.Close();
wt.Close();
myfile.Close();
I am trying to increment an integer value in the file banking.txt, but I am getting the following error:
Cannot access a closed file
Perhaps it's because you're closing rd before wt?
If that is the case, I would recommend using the using statement to prevent this confusion in the future:
int AccNum;
using (FileStream myfile = new FileStream("C:\\bankin.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)) {
using (StreamReader rd = new StreamReader(myfile)) {
using (StreamWriter wt = new StreamWriter(myfile)) {
int a = Convert.ToInt32(rd.ReadLine());
AccNum = a;
a += 1;
wt.WriteLine(Convert.ToString(a));
Console.WriteLine(rd.ReadLine());
}
}
}
Change your code to make use of the using statements
Provides a convenient syntax that ensures the correct use of
IDisposable objects.
int AccNum;
using(FileStream myfile = new FileStream("C:\\bankin.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
using(StreamReader rd = new StreamReader(myfile))
using (StreamWriter wt = new StreamWriter(myfile))
{
int a = Convert.ToInt32(rd.ReadLine());
AccNum = a;
a += 1;
wt.WriteLine(Convert.ToString(a));
Console.WriteLine(rd.ReadLine());
}
int AccNum;
using(FileStream myfile = new FileStream("C:\\bankin.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using(StreamReader rd = new StreamReader(myfile))
{
using(StreamWriter wt = new StreamWriter(myfile))
{
int a = Convert.ToInt32(rd.ReadLine());
AccNum = a;
a += 1;
wt.WriteLine(Convert.ToString(a));
}
Console.WriteLine(rd.ReadLine());
}
}
It's good practice to use 'using'.
the exception is produced by the line wt.Close() because the file is already closed. the Close method on StreamReader close stream and all the underlying resources (see http://msdn.microsoft.com/en-us/library/system.io.streamreader.close.aspx)
and I assume that you want to save changes, so use Flush to save or use Close with AutoFlush in place of Flush. here is your example with some modification
int AccNum;
using (FileStream myfile = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (StreamReader rd = new StreamReader(myfile))
{
using (StreamWriter wt = new StreamWriter(myfile))
{
int a = Convert.ToInt32(rd.ReadLine());
AccNum = a;
a += 1;
wt.WriteLine(Convert.ToString(a));
Console.WriteLine(rd.ReadLine());
wt.Flush();
}
}
}

If i stop CryptoStream Read i get Bad Data exception

I'm having problem with CryptoStream Decryptor.
I'm decrypting file on another Thread.
So here is the problem:
When I let the file to decrypt to the end, everything is allright but when I stop thread, using global variable, and get out of while loop
while( !stopThread && ( nBRead = csFile.Read(readbuf, 0, 8192)) != 0)
I get Bad Data exception at thecryptostream Dispose().
What i'm doing wrong ??
Here's my code:
string ext;
//textBox1.Text = "";
OpenFileDialog ofdFile = new OpenFileDialog();
if (textMode)
ofdFile.Title = "Please select text to decrypt.";
else
ofdFile.Title = "Please select file to decrypt.";
OpenFileDialog ofdKey = new OpenFileDialog();
ofdKey.Title = "Please select KEY.";
// mora ovo ili invoke koga nema dialog :)
originalContex.Send(delegate
{
dialogRes = ofdFile.ShowDialog();
dialogResKey = ofdKey.ShowDialog();
}, null);
if ( dialogRes == DialogResult.OK && dialogResKey == DialogResult.OK )
{
FileStream fsKey = new FileStream(ofdKey.FileName, FileMode.Open);
byte[] iv = new byte[8];
byte[] key = new byte[24];
byte[] extB = new byte[20];
fsKey.Read(iv, 0, 8);
fsKey.Read(key, 0, 24);
fsKey.Read(extB, 0, 20);
fsKey.Dispose();
FileStream fsOpenedFile = new FileStream(ofdFile.FileName, FileMode.Open, FileAccess.Read);
CryptoStream csFile = new CryptoStream(fsOpenedFile, new TripleDESCryptoServiceProvider().CreateDecryptor(key, iv), CryptoStreamMode.Read);
if (textMode)
{
int readbuf;
List<byte> lb = new List<byte>();
while ((readbuf = csFile.ReadByte()) != -1)
lb.Add((byte)readbuf);
textBox1.Invoke( new MethodInvoker(() => { textBox1.Text = Encoding.UTF8.GetString(lb.ToArray()); }) );
prog.Invoke(new MethodInvoker(() => { prog.Value = 100; }));
}
else // filemode
{
byte[] readbuf = new byte[8192];
ext = Encoding.UTF8.GetString(extB).Trim('\0');
string saveDir = Path.GetDirectoryName(ofdFile.FileName) + "\\" + Path.GetFileNameWithoutExtension(ofdFile.FileName) + "_DECRYPTED";
Directory.CreateDirectory( saveDir );
Directory.SetCurrentDirectory( saveDir );
FileStream fsDecrFile = new FileStream(Path.GetFileNameWithoutExtension(ofdFile.FileName) + ext, FileMode.Create, FileAccess.Write);
FileInfo fi = new FileInfo(ofdFile.FileName);
long oneProc = fi.Length / 100;
int nBRead = 0;
long nBReadacc = 0;
while ( !stopThread && ( nBRead = csFile.Read(readbuf, 0, 8192)) != 0 )
{
nBReadacc += nBRead;
fsDecrFile.Write(readbuf, 0, nBRead);
if (nBReadacc >= oneProc)
{
nBReadacc = 0;
prog.Invoke(new MethodInvoker(() => { prog.Value +=1; }));
}
}
try
{
csFile.Dispose();
}
catch (CryptographicException e)
{
MessageBox.Show(e.Message);
}
// MessageBox.Show(nBReadacc.ToString());
fsDecrFile.Flush();
fsDecrFile.Dispose();
prog.Invoke(new MethodInvoker(() => { prog.Value = 100; }));
}
fsOpenedFile.Dispose();
// csFile.CopyTo
}
ofdFile.Dispose();
ofdKey.Dispose();
}

Categories