Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string in file using a SQL procedure

I have a method to remove string from file written in C# for SQL Server:

[SqlProcedure]
public static void fileReplace(string path, string patternToReplace, string stringForReplace)
{
    using (SqlConnection connection = new SqlConnection("context connection=true"))
    {
        connection.Open();
        try
        {
            File.WriteAllText(path, Regex.Replace(File.ReadAllText(path), patternToReplace, stringForReplace));
        }
        catch (Exception e)
        {
        }
    }
}

Assembly and procedure in SQL Server are created like this:

CREATE ASSEMBLY FileUtils 
  FROM '<path>\<name>.dll'
  WITH PERMISSION_SET = EXTERNAL_ACCESS
GO

CREATE PROCEDURE fileReplace (
         @path             nvarchar(max)  
       , @patterToReplace  nvarchar(max)  
       , @stringForReplace nvarchar(max)  
      )
AS EXTERNAL NAME FileUtils.FileUtils.fileReplace;
GO

The method in C# is working correct, but when I call it from SQL Server, nothing happens (file doesn't change). What's wrong?

like image 714
user1733773 Avatar asked Dec 06 '25 02:12

user1733773


1 Answers

you SQLServer login needs to have permission to that file. It's possible that when it tries to read/write file it fails with exception, but exception supressed by try catch

like image 71
Roman Pekar Avatar answered Dec 08 '25 16:12

Roman Pekar