예제 #1
0
 static void Main(string[] args)
 {
     var parsedArgs = Parser.Default.ParseArguments <SqlBinaryToFileOptions>(args)
                      .MapResult(
         (SqlBinaryToFileOptions opts) => SqlBinaryToFileOptions.Process(opts),
         errs => 1
         );
 }
예제 #2
0
            public static int Process(SqlBinaryToFileOptions opts)
            {
                string query = "";

                if (opts.FromFile)
                {
                    query = File.ReadAllText(opts.Query);
                }
                else
                {
                    query = opts.Query;
                }

                using (SqlConnection conn = new SqlConnection(opts.ConnectionString))
                {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand(query, conn))
                    {
                        cmd.CommandType = System.Data.CommandType.Text;
                        var reader = cmd.ExecuteReader();

                        while (reader.Read())
                        {
                            string fileName = opts.FileNameTemplate;
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                var fieldName = reader.GetName(i);
                                if (fieldName.ToLower() != opts.BinaryFieldName.ToLower())
                                {
                                    fileName = fileName.Replace($"{{{fieldName}}}", reader.GetString(i));
                                }
                            }

                            var    binary    = reader.GetSqlBinary(reader.GetOrdinal(opts.BinaryFieldName));
                            byte[] binaryVal = new byte[0];
                            if (!binary.IsNull)
                            {
                                binaryVal = binary.Value;
                            }

                            File.WriteAllBytes(fileName, binaryVal);
                        }
                    }
                }

                return(0);
            }