文件路径未保存在SQL数据库中

时间:2020-01-25 08:02:07

标签: c# ado.net

我无法将文件路径保存到SQL数据库中。我需要保存它,以便以后可以检索该文件。

因此,基本上,该应用程序的作用是连续监视特定文件夹中的所有更改。因此,添加文件时,它会检测到该文件,然后将该文件保存在数据库中。现在我不确定这里的最佳实践是保存文件还是仅保存文件路径?

这是我目前正在测试的代码:

static void Main(string[] args)
{
    string path = "C:\\Documents";
    MonitorDirectory(path);
    Console.ReadKey();
} 

private static void MonitorDirectory(string path)
{
    FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
    fileSystemWatcher.Path = path;
    fileSystemWatcher.Created += FileSystemWatcher_Created;
    fileSystemWatcher.Renamed += FileSystemWatcher_Renamed;
    fileSystemWatcher.Deleted += FileSystemWatcher_Deleted;
    fileSystemWatcher.EnableRaisingEvents = true;
}

private static void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("File created: {0}", e.Name);

    string connectionString = @"Data Source=Development-PC\SQLEXPRESS;Initial 
    Catalog=FileDB;Integrated Security=True";
    FileStream stream = new FileStream(e.Name, FileMode.Open, FileAccess.ReadWrite);
    BinaryReader reader = new BinaryReader(stream);
    byte[] file = reader.ReadBytes((int)stream.Length);
    reader.Close();
    stream.Close();
    DateTime dateTimeVariable = DateTime.Now;
    SqlCommand command;
    SqlConnection connection = new SqlConnection(connectionString);
    command = new SqlCommand("INSERT INTO FileTable (filename, datestamp) VALUES (@filename, 
    @datestamp)", connection);
    command.Parameters.Add("@filename", SqlDbType.Binary, file.Length).Value = file;
    command.Parameters.Add("@datestamp", SqlDbType.DateTime, file.Length).Value = 
    dateTimeVariable;
    connection.Open();
    command.ExecuteNonQuery();
}

我遇到的错误是在第42行:

command.Parameters.Add("@filename", SqlDbType.Binary, file.Length).Value = file;

哪个是

未处理的异常。 System.NullReferenceException:对象引用未设置为对象的实例。

任何帮助将不胜感激!

谢谢

1 个答案:

答案 0 :(得分:1)

@GSerg是正确的,您的代码有很多问题。如果只需要文件名,则不必读取文件。 import UIKit class DrawExamples: UIView { override func drawRect(rect: CGRect) { // context is the object used for drawing let context = UIGraphicsGetCurrentContext() CGContextSetLineWidth(context, 3.0) CGContextSetStrokeColorWithColor(context, UIColor.purpleColor().CGColor) /* //straight line CGContextMoveToPoint(context, 30, 30) CGContextAddLineToPoint(context, 150, 320) */ CGContextMoveToPoint(context, 50, 50) CGContextAddLineToPoint(context, 90, 130) CGContextAddLineToPoint(context, 180, 100) CGContextAddLineToPoint(context, 90, 60) CGContextAddLineToPoint(context, 90, 130) //Actually draw the path CGContextStrokePath(context) } } 可以为您提供该信息。如果您需要阅读并保存内容,则需要在数据库中添加一个filecontent字段。

FileInfo