user2515462
user2515462

Reputation:

How to update with an id code?

My code is working like this: when I create a file in a folder, the database will get information about the file.|

query = "INSERT INTO files (name,size,last_edit,extension) VALUES('" + name + "','" +  
size + "',now(),'" + extension + "')";

This is the example. When i change the file, the database will UPDATE the information about the file. When i delete the file, the database will DELETE the information about the file

My question is: Now when i rename it in the folder, how do i rename it in the database? cause i can't think about anything to use at the "Where ...=" Size wont work, Name wont work(since the name is changed), last_edit wont work(since it changes all the time), extension wont work(since there could be multiple files with the same extension. So i created a primary key(ID)

This is how i created my table:

create table files (ID int not null auto_increment,name varchar(50),size
int,last_edit datetime,extension varchar(5), primary key (id));

I thought that i could do something with ID. But I don't have a clue how to make sure he chooses the right ID.

    private void fileSystemWatcher1_Renamed(object sender, System.IO.RenamedEventArgs e)
    {
        listBox1.Items.Add("File renamed> " + e.FullPath + " -Date:" + DateTime.Now);
        name = e.Name;
        extension = Path.GetExtension(e.FullPath);
        size = e.Name.Length;
        query = "update files set name='"+name+"' where ID=";
        query();
    }

My event Renamed.

Upvotes: 0

Views: 97

Answers (1)

Leri
Leri

Reputation: 12535

As far as I understood question you need to update database when file is renamed. To get notified when file is modified you can use System.IO.FileSystemWatcher class.

For example:

static void Main(string[] args)
{
    //Creating test file. Can be removed.
    File.WriteAllText("test.txt", "test");
    // object that will watch changes for your file on file system
    string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); //get current path.
    var watcher = new FileSystemWatcher(path);
    watcher.Renamed += watcher_Renamed;
    watcher.EnableRaisingEvents = true;
}

private static void watcher_Renamed(object sender, RenamedEventArgs e)
{
    // This event is fired when file is renamed. Do your own stuff here.
    Console.WriteLine(e.OldName + " => " + e.Name);
}

Edit:

private void fileSystemWatcher1_Renamed(object sender, System.IO.RenamedEventArgs e)
{
    listBox1.Items.Add("File renamed> " + e.FullPath + " -Date:" + DateTime.Now);
    name = e.Name;
    extension = Path.GetExtension(e.FullPath);
    size = e.Name.Length;
    query = "update files set name='"+name+"' where `name`='" + e.OldName + "'";
    query();
}

Upvotes: 1

Related Questions