c# File used by who? - c#

I want history links for Google Chrome and when i search, i found 'History' file of Google Chrome.
But i can't read 'History' file because Google Chrome use this 'History' file. Therefore firstly i copy 'History' file
and i read 'History' file that i copied.It worked but only once. Because when the second time i want history links,
I get "File used by another Process" error(For it can't delete).
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
string userName = Environment.UserName;
string confilename = string.Format(#"Data Source=C:\Users\{0}\Desktop\History1827", userName);
string oldfilename = string.Format(#"C:\Users\{0}\AppData\Local\Google\Chrome\User Data\Default\History", userName);
string newfilename = string.Format(#"C:\Users\{0}\Desktop\History1827", userName);
File.Copy(oldfilename, newfilename); // I copy oldfile to newfile destination
using (SQLiteConnection connection = new SQLiteConnection(confilename))
{
connection.Open();
SQLiteCommand command1 = new SQLiteCommand();
command1.Connection = connection;
command1.CommandText = "Select * From urls";
SQLiteDataReader dr = command1.ExecuteReader();
string historylinks = "";
while (dr.Read())
{
// dr[0] = ID of Link , dr[1] = Link , dr[2] = Title of Link
historylinks = dr[0].ToString() + "\t--->" + dr[1].ToString(); // I get ID and Link from History file that i copied
listBox1.Items.Add(historylinks);
}
dr.Close();
connection.Close();
}
if (File.Exists(newfilename))
{
File.Delete(newfilename);
MessageBox.Show("Deleted");
}
}
Error : File.Delete(newfilename);
What did i do after that when i see this error?
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
string userName = Environment.UserName;
string confilename = string.Format(#"Data Source=C:\Users\{0}\Desktop\History1827", userName);
string oldfilename = string.Format(#"C:\Users\{0}\AppData\Local\Google\Chrome\User Data\Default\History", userName);
string newfilename = string.Format(#"C:\Users\{0}\Desktop\History1827", userName);
File.Copy(oldfilename, newfilename); // I copy oldfile to newfile destination
//------ I DID NOT USE SQLİTECONNECTİON -----
//using (SQLiteConnection connection = new SQLiteConnection(confilename))
//{
// connection.Open();
// SQLiteCommand command1 = new SQLiteCommand();
// command1.Connection = connection;
// command1.CommandText = "Select * From urls";
// SQLiteDataReader dr = command1.ExecuteReader();
// string historylinks = "";
// while (dr.Read())
// {
// // dr[0] = ID of Link , dr[1] = Link , dr[2] = Title of Link
// historylinks = dr[0].ToString() + "\t--->" + dr[1].ToString(); // I get ID and Link from History file that i copied
// listBox1.Items.Add(historylinks);
// }
// dr.Close();
// connection.Close();
//}
if (File.Exists(newfilename))
{
File.Delete(newfilename);
MessageBox.Show("Deleted");
}
}
It worked. So, if i don't use SQLiteConnection, Program can delete 'History' file that it copied .
Who use this 'History' file that was copied? How can i fix ?
Thank you.

You can try Process Explorer to find which application opened the file handle. If Process Explorer cannot find that, use Process Monitor to trace which process is trying to access the file.

Related

Get path of sqlite database file

Hi everyone i can't set a relative path to open my database, the project is structured in this mood
projectname
db/acces.db
info/try.cs
This is the code inside try.cs with which i should open the database, obviously if I put the full path it goes:
try {
using (SQLiteConnection conn = new SQLiteConnection(#"data source="db/access.db")
{
conn.Open();
using (SQLiteCommand fmd = conn.CreateCommand()){
fmd.CommandText = #"SELECT * FROM 'test';
fmd.CommandType = CommandType.Text;
SQLiteDataReader r = fmd.ExecuteReader();
while (r.Read())
Debug.Writeline("foo");
conn.Close();
}
}
catch (Exception e){
Debug.WriteLine("Errors");
}
I should take the path of the acces.db file, not complete but relative to my project, to be set in data source, how should i do?
You can use something like this:
using System.IO;
var connection = "Data Source=" + Path.Combine(Directory.GetCurrentDirectory(), "db\\access.db")
try {
using (SQLiteConnection conn = new SQLiteConnection(connection)
{
conn.Open();
using (SQLiteCommand fmd = conn.CreateCommand()){
fmd.CommandText = #"SELECT * FROM 'test';
fmd.CommandType = CommandType.Text;
SQLiteDataReader r = fmd.ExecuteReader();
while (r.Read())
Debug.Writeline("foo");
conn.Close();
}
}
catch (Exception e){
Debug.WriteLine("Errors");
}
You said you should get something of type Data Source=C:\\Users\\mypc\\Documents\\tesrepo\\Myapp\\testApp\\db\\test.db.
Here is how to get the correct path.
Project path:
Directory.GetParent(workingDirectory).Parent.FullName;
Add the path you want at the end: For example, the address of the 123.mp3 file in the music folder here is:
string filepath = Path.Combine(projectDirectory + "\\music\\123.mp3");
//Get db address
string workingDirectory = Environment.CurrentDirectory;
string projectDirectory = Directory.GetParent(workingDirectory).Parent.FullName;
string dbpath = Path.Combine(projectDirectory + "\\db\\test.db");
dbpath is what you want.
If you have any questions about my code, please add a comment below.
Updated:
You can import the updated file into the output directory through this operation.
Your path would work without any modification.

How to read data from database & write it on a txt file?

I want to retrieve data from the server database using windows services on a text file?Can i do that?How will i do that?I mean i know to create a window service but i am confused with the SQL connection and file writing part where to execute it?i have tried something
class Program
{
static void Main(string[] args)
{
RunSchedule();
}
public static void RunSchedule()
{
string path = Path.GetFullPath("d:\\MyTest") + "\\" + DateTime.Now.ToString("MM_dd_yyyy_HH_mm") + "_Log.txt";
try
{
if (!File.Exists(path))
{
File.Create(path);
SqlConnection conn = new SqlConnection("Data Source=...;Initial Catalog=Test;User ID=s_a;Password=sa56ta112;");
String sql = #"SELECT Id,UserName, Email,Password,CreatedDate
FROM Register";
SqlCommand com = new SqlCommand();
com.CommandText = sql;
//com.Connection = conn;
conn.Open();
StreamWriter tw = File.AppendText("d:\\MyTest");
SqlDataReader reader = com.ExecuteReader();
tw.WriteLine("Id,UserName,Email,Password,CreatedDate");
while (reader.Read())
{
tw.Write(reader["Id"].ToString());
tw.Write(" , " + reader["UserName"].ToString());
tw.Write(" , " + reader["Email"].ToString());
tw.Write(" , " + reader["Password"].ToString());
tw.Write(" , " + reader["CreatedDate"].ToString());
}
tw.WriteLine(DateTime.Now);
tw.WriteLine("---------------------------------");
tw.Close();
reader.Close();
conn.Close();
}
}
catch (Exception ex)
{
string errorLogPath = #"D:\MyTest.txt";
File.AppendAllText(errorLogPath, Environment.NewLine + ex.Message);
}
}
}
am i doing it correct? Please guide me.
while (reader.Read())
{
row = new DataRow();
row.ItemArray = new object[reader.FieldCount];
reader.GetValues(row.ItemArray);
foreach (object item in row.ItemArray)
{
streamWriter.Write((string)item + "\t");
}
streamWriter.WriteLine();
}
If you get "Access to the path 'd:\MyTest' is denied." error than go to the txt file properties in the solution explorer and than change the Copy to output directory property from Do not copy into Copy if newer or Copy always

Delete the old image when it has to upload new image

this is so that when I need to upload a right an image to an article so it must delete the old image
and it must be clear in the folder where the image is located,
string Tid = DateTime.Now.Ticks.ToString();
string unikID = Guid.NewGuid().ToString();
string url = "~/img/bimg/";
cmd.CommandText = "SELECT img FROM aktiviteter WHERE Id = #id;";
cmd.Parameters.AddWithValue("#Id", id);
conn.Open();
SqlDataReader readerImg = cmd.ExecuteReader();
if (readerImg.Read())
{
File.Delete(Server.MapPath(url.Remove(0, 1) + readerImg["img"]));
}
conn.Close();
problem is that I need to find the image in the column in the database where the entity who should delete the picture
Access to the path 'C:\Users\198407\Documents\Visual Studio 2013\WebSites\Jesper-mm-CRUD\img\bimg\' is denied.
my pictures located here: /img/bimg/hello.png
how it looks when I load to the server
string Tid = DateTime.Now.Ticks.ToString();
string unikID = Guid.NewGuid().ToString();
string url = "~/img/bimg/";
cmd.CommandText = "SELECT img FROM aktiviteter WHERE Id = #id;";
cmd.Parameters.AddWithValue("#Id", id);
conn.Open();
SqlDataReader readerImg = cmd.ExecuteReader();
if (readerImg.Read())
{
File.Delete(Server.MapPath(url.Remove(0, 1) + readerImg["img"]));
}
conn.Close();
ImageNet.FluentImage img = ImageNet.FluentImage.FromStream(FileUploadImg.FileContent);
img.Resize.Scale(360).Save(Server.MapPath(url + unikID + ".png"));
if (File.Exists(Server.MapPath(url + unikID + ".png")))
{
cmd.CommandText = "UPDATE aktiviteter SET navn = #navn, sted = #sted, indhold = #indhold, img = #img, rubrik = #rubrik, retbrugerID = #retbrugerid WHERE Id = #id;";
cmd.Parameters.AddWithValue("#Id", id);
cmd.Parameters.AddWithValue("#navn", navn);
cmd.Parameters.AddWithValue("#sted", Sted);
cmd.Parameters.AddWithValue("#indhold", Indhold);
cmd.Parameters.AddWithValue("#img", unikID);
cmd.Parameters.AddWithValue("#rubrik", rubrik);
cmd.Parameters.AddWithValue("#retbrugerid", brugerid);
}
Since you are getting this error -
Access to the path 'C:\Users\198407\Documents\Visual Studio
2013\WebSites\Jesper-mm-CRUD\img\bimg\' is denied.
I would suggest , granting read/write access to this user = IIS_IUSRS for required directory.
Read more helpful link

Retrieve image from MySQL database and display on webpage using c#

I am using asp.net with c# to build website, but now i come into a problem. I insert image with blob type into mysql database but i cannot retrieve it. There is no picturebox layout for web controls. I want to use image.imageURL to display this image. I searched a lot, some recommend use another aspx page, some recommend using ashx, but i cannot find a detailed solution. Here is what i have now:
protected void Button1_Click(object sender, EventArgs e)
{
String myname = Request.QueryString["Name"];
string myConnection = "server=127.0.0.1;uid=root;" + "pwd=81210ZLK;database=database;" + "Allow User Variables=True";
try
{
MySqlConnection myConn = new MySqlConnection(myConnection);
myConn.ConnectionString = myConnection;
MySqlCommand SelectCommand = new MySqlCommand();
string mySQL = "SELECT iddb1,fullname,age,gender,healthrecord,headpicture FROM database.db1 where fullname = #myname ";
SelectCommand.CommandText = mySQL;
SelectCommand.Parameters.AddWithValue("#myname", myname);
SelectCommand.Connection = myConn;
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
while (myReader.Read())
{
Int16 ID = myReader.GetInt16(0);
string FName = myReader.GetString(1);
Int16 FAge = myReader.GetInt16(2);
string FGender = myReader.GetString(3);
string FRecord = myReader.GetString(4);
ShowID.Text = ID.ToString();
ShowName.Text = FName.ToString();
ShowAge.Text = FAge.ToString();
ShowGender.Text = FGender.ToString();
ShowRecord.Text = FRecord.ToString();
byte[] imgg = (byte[])(myReader["headpicture"]);
if (imgg == null)
Image1.ImageUrl = null;
else {
MemoryStream mstream = new MemoryStream(imgg);
// Image1.ImageURL = System.Drawing.Image.FromStream(mstream);
}
}
myConn.Close();
}
catch (Exception ex)
{
MessageBoxShow(this, ex.Message);
}
}
Here come with the problem and i marked it with \\
Try this ,
Image1.ImageURL = "data:image/jpeg;base64,"+Convert.ToBase64String(imgg);

Want to see the ouput "data.csv" in the desktop or any location

public void CreateFileOutput(object parameter)
{
string workSheetName, targetFile;
workSheetName = "data"; targetFile = "data.csv";
string strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + SourceAppFilePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';";
OleDbConnection conn = null;
StreamWriter wrtr = null;
OleDbCommand cmd = null;
OleDbDataAdapter da = null;
try
{
conn = new OleDbConnection(strConn);
conn.Open();
cmd = new OleDbCommand("SELECT * FROM [" + workSheetName + "$]", conn);
cmd.CommandType = CommandType.Text;
wrtr = new StreamWriter(targetFile);
da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
for (int x = 0; x < dt.Rows.Count; x++)
{
string rowString = "";
for (int y = 0; y < dt.Columns.Count; y++)
{
rowString += "\"" + dt.Rows[x][y].ToString() + "\",";
}
wrtr.WriteLine(rowString);
}
Console.WriteLine();
Console.WriteLine("Done! Your " + SourceAppFilePath + " has been converted into " + targetFile + ".");
Console.WriteLine();
}
catch (Exception exc)
{
Console.WriteLine(exc.ToString());
Console.ReadLine();
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Dispose();
cmd.Dispose();
da.Dispose();
wrtr.Close();
wrtr.Dispose();
}
}
XLS file is being converted to csv.I am able to see that in the for loop wrtr.WriteLine(rowString);
But I want to see the final output file "Data.csv" in the desktop location as I am taking the source .xls file from the desktop. Provide me a solution. Thanks.
You need to use the full path to save the file to the desktop. You can get the path using the Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory, like this:
string targetFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string targetPath = Path.Combine(targetFolder, "Data.csv");
Then use FileStream with the full path:
fs = new FileStream(targetPath, FileMode.Create);
Edited Per Comments Below
The key to this is specifying the path to where you want to save the file. Just giving a file name will put it in the directory the application is excuting from. An easy way to do this would be to use the GetDirectoryName method of the Path class. Assuming the file was passed in, read from a config file, hard coded, etc:
string path = Path.GetDirectoryName(sourceFile);
string target = path + #"\" + "Data.csv";
If the sourceFile was C:\Data\Input.xml, then path would equal "C:\Data", and target would be C:\Data\Data.csv.
The advantage here is that you can pass a filename with the path, and it will always place the targetfile in the same location. This lends itself nicely to parameterization of the method, or maybe even having the user select the file through an OpenFileDialog box or similar mechanism.
Additional Edit Per John's Comment
Based on the code you posted, the Data.xsl file is in the executing application's folder. In that case, you'd simply need to do the following:
fs = new FileStream("data.csv", FileMode.Create);
No need to mess with paths, as the filestream will also go to the executing application's directory.
In the end, it's all about using the information available from the sourcefile (i.e., it's location/path data) and applying it to the target file's full path and name.

Categories

Resources