使用Windows服务将文件转换为base64字符串 [英] Convert file to base64 string using windows service

查看:110
本文介绍了使用Windows服务将文件转换为base64字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我试图将文件转换为base64String,然后将该字符串存储在文本文件中。我想要创建的是一个Windows服务 - 只要在某个文件夹中创建一个文件。服务创建一个日志文件,说一个文件已被添加到文件夹,然后它应该将该文件转换为base64String并将该字符串存储在文本文件中。



编辑1:

我试图将文件转换为base64String。下面的代码成功注册了一个新文件被添加到文件夹。我现在尝试做的是将刚刚添加到base64String的文件转换为将该字符串存储在单独的文件中。要转换为base64String的代码在方法 ConvertToBase64()中,该方法在 FileSystemWatcher1_Created()中调用。我试过的可以在下面看到

我希望能够将任何文件转换为添加到某个文件夹的base64String

我的代码



Hi im trying to convert a file to a base64String and then store that string in a text file. What i am trying to create is a Windows Service - As soon as a file is created in a certain folder.The Service creates a Log file to say that a file has been added to the folder put then it should convert that file into a base64String and store that string in a text file.

EDIT 1:
Im trying to convert a file into a base64String.The code below successfully registers a new file being added to a folder. What im trying to do now is convert that file that has just been added to a base64String and store that string in a separate file. To code to convert to base64String is in the method ConvertToBase64(), That method is being called inside FileSystemWatcher1_Created(). What i have tried can be seen below
I Want to be able convert any file to a base64String that is added to certain folder
My Code

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Threading;
using System.Reflection;

namespace WindowsServiceFolderWatcher
{
    public partial class Service1 : ServiceBase
    {
        string WatchPath1 = ConfigurationManager.AppSettings["WatchPath1"];  
        public Service1()
        {
            InitializeComponent();
            fileSystemWatcher1.Created += fileSystemWatcher1_Created;
          

        }

        internal void TestStartupAndStop(string[] args)
        {
            this.OnStart(args);
            Console.ReadLine();
            this.OnStop();
        }
        FileSystemWatcher myWatcher = new FileSystemWatcher();
        protected override void OnStart(string[] args)
        {

            try
            {
                fileSystemWatcher1.Path = WatchPath1;

                
            }
            catch (Exception ex)
            {
                throw ex;
            }  
        }

        protected override void OnStop()
        {
            try
            {
                Create_ServiceStopTextFile();
            }
            catch (Exception ex)
            {

                throw ex;
            } 
        }
        void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
        {
            try
            {
                Thread.Sleep(7000);
                if(CheckFileExistance(WatchPath1, e.Name))
                {
                    CreateTextFile(WatchPath1, e.Name);
                    ConvertToBase64(/*WatchPath1, e.Name*/);
                   // Copy_Excelfile_And_Paste_at_anotherloaction_OnServiceStart(WatchPath1, e.Name);
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
        
        private bool CheckFileExistance(string FullPath, string FileName)
        {
            // Get the subdirectories for the specified directory.'  
            bool IsFileExist = false;
            DirectoryInfo dir = new DirectoryInfo(FullPath);
            if (!dir.Exists)
                IsFileExist = false;
            else
            {
                string FileFullPath = Path.Combine(FullPath, FileName);
                if (File.Exists(FileFullPath))
                    IsFileExist = true;
            }
            return IsFileExist;


        }

        private void CreateTextFile(string FullPath, string FileName)
        {

            StreamWriter SW;

            if (!File.Exists(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txtStatus_" + DateTime.Now.ToString("MMddyyyy") + ".txt")))
            {
                SW = File.CreateText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txtStatus_" + DateTime.Now.ToString("MMddyyyy") + ".txt"));
                //SW = File.CreateText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txtBase64_" + DateTime.Now.ToString("MMddyyyy") + ".txt"));
                SW.Close();
            }
            using (SW = File.AppendText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txtStatus_" + DateTime.Now.ToString("MMddyyyy") + ".txt")))
            {
                SW.WriteLine("File Created with Name: " + FileName + " at this time: " + DateTime.Now.ToString("HH:mm , MM/dd/yyyy"));
                // + FilePath
               
                SW.Close();
            }

           // Copy_Excelfile_And_Paste_at_anotherloaction_OnServiceStart();
        
        }

        public static void ConvertToBase64(/*string FullPath, string FileName*/)
        {

            //First Attempt
            //string tiff = FullPath;
            //FileStream fstream = new FileStream(tiff, FileMode.Open);
            //byte[] original = new byte[fstream.Length];
            //fstream.Read(original, 0, (int)fstream.Length);
            //int fstreamLength = (int)fstream.Length;
            //string tiffBase64 = Convert.ToBase64String(original);

            //StreamWriter writer = new StreamWriter(@"C:\\Users\\username\\Desktop\\Base64\\SampleBase64.txt");
            //writer.Write(tiffBase64);
            //writer.Close();
            //fstream.Close();

            //Second Attempt
            using (System.IO.Stream s = new System.IO.FileStream(@"C:\\Users\\username\\Desktop\\Ball.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                var bytes = StreamHelper.ReadToEnd(s);

                var string64 = Convert.ToBase64String(bytes);

                //Console.WriteLine(/*"Size " +*/ string64);
                File.WriteAllBytes(@"C:\\Users\\username\\Desktop\\Base64\\Base.txt", Convert.FromBase64String(string64));
                //var bytes2 = Convert.FromBase64String(string64);
                //bytes.WriteAllBytes(@"C:\Users\username\Desktop\output24.pdf", bytes2);

               

            }


        

        }

        public static void Create_ServiceStopTextFile()
        {
            string Destination = "C:\\Users\\username\\Desktop\\FileWatcherWinService";
            StreamWriter SW;
            if (Directory.Exists(Destination))
            {
                Destination = System.IO.Path.Combine(Destination, "txtServiceStop_" + DateTime.Now.ToString("yyyyMMdd") + ".txt");
                if (!File.Exists(Destination))
                {
                    SW = File.CreateText(Destination);
                    SW.Close();
                }
            }
            using (SW = File.AppendText(Destination))
            {
                SW.Write("\r\n\n");
                SW.WriteLine("Service Stopped at: " + DateTime.Now.ToString("dd-MM-yyyy H:mm:ss"));
                SW.Close();
            }

        }

        public static void Copy_Excelfile_And_Paste_at_anotherloaction_OnServiceStart()
        {
            try
            {
                string source = "C:\\Users\\username\\Desktop\\Documents";
                string Destination = "C:\\Users\\username\\Desktop\\Destination";
                string filename = string.Empty;
                if (!(Directory.Exists(Destination) && Directory.Exists(source)))
                    return;
                string[] Templateexcelfile = Directory.GetFiles(source);
                foreach (string file in Templateexcelfile)
                {
                    if (file.Contains("Excel"))
                    {
                        filename = System.IO.Path.GetFileName(file);
                        Destination = System.IO.Path.Combine(Destination, filename.Replace(".xlsx", DateTime.Now.ToString("yyyyMMdd")) + ".xlsx");
                        System.IO.File.Copy(file, Destination, true);
                    }
                }

            }
            catch (Exception ex)
            {
                Create_ServiceStopTextFile();
            }

        }
        internal void DebugMode()
        {
            this.OnStart(null);
        }
    }
}





我尝试了什么:





What I have tried:

  //First Attempt
            //string tiff = FullPath;
            //FileStream fstream = new FileStream(tiff, FileMode.Open);
            //byte[] original = new byte[fstream.Length];
            //fstream.Read(original, 0, (int)fstream.Length);
            //int fstreamLength = (int)fstream.Length;
            //string tiffBase64 = Convert.ToBase64String(original);

            //StreamWriter writer = new StreamWriter(@"C:\\Users\\username\\Desktop\\Base64\\SampleBase64.txt");
            //writer.Write(tiffBase64);
            //writer.Close();
            //fstream.Close();

//Second Attempt
            using (System.IO.Stream s = new System.IO.FileStream(@"C:\\Users\\username\\Desktop\\Ball.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                var bytes = StreamHelper.ReadToEnd(s);

                var string64 = Convert.ToBase64String(bytes);

                //Console.WriteLine(/*"Size " +*/ string64);
                File.WriteAllBytes(@"C:\\Users\\username\\Desktop\\Base64\\Base.txt", Convert.FromBase64String(string64));
                //var bytes2 = Convert.FromBase64String(string64);
                //bytes.WriteAllBytes(@"C:\Users\username\Desktop\output24.pdf", bytes2);

               

            }

推荐答案

我陷入了将新创建的文件转换为base64String的部分。之前我创建了一个应用程序,它接受了一个硬编码文件并将其转换为base64String。我试图使用相同但现在使用任何文件。

所有你要做的就是用 FileSystemEventArgs.FullPath Property(System.IO) [ ^ ]当事件被触发时,你被交给 fileSystemWatcher1_Created 事件处理程序! />
假设您的服务对该文件夹具有适当的访问权限(默认情况下可能没有,它不会在您的用户帐户下运行)它应该可以正常工作。
"I'am stuck at the part where the newly created file is converted to a base64String. Previously i created an application that took a hardcoded file and turned it into a base64String. im trying to to the same but with any file now."
All you have to do is replace the hardcoded path with the FileSystemEventArgs.FullPath Property (System.IO)[^] you are handed in the fileSystemWatcher1_Created event handler when the event is fired!
Assuming your service has the appropriate access permissions on the folder (and it may not by default, it doesn't run under your user account) it should work.


这篇关于使用Windows服务将文件转换为base64字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆