uploading files to Google drive with windows service

Siwar Ha

Member
Joined
May 28, 2021
Messages
5
Programming Experience
Beginner
I m writhing a program that moves files from one place to another and if everything is fine a copy of those files are sent .zip to google drive .

the code is working fine with console application : files are placed in the destination and uploaded to google drive . BUT when i run it as windows service installed on my machine : the files are moved but nothing happen in google drive .

i don't know where is exactly the problem ? Any help ?

this is the code to upload to google drive:
public class RepositoryGoogleDrive : IDisposable
{
    public void Dispose() { }
    static string[] Scopes = { DriveService.Scope.Drive,
                   DriveService.Scope.DriveAppdata,
                   DriveService.Scope.DriveFile,
                   DriveService.Scope.DriveMetadataReadonly,
                   DriveService.Scope.DriveReadonly,
                   DriveService.Scope.DriveScripts };
 
    public static DriveService Execution( string ApplicationName , string credentials)
    {
        UserCredential credential;
       // credentials = "C:/workspace/datawarehous/TMP/credentials.json";
        using (var stream =
            new FileStream(credentials, FileMode.Open, FileAccess.Read))
        {

            string credPath = "token.json";
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "XXXX",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
        }
        // Create Drive API service.
        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });

        // Define parameters of request.
        FilesResource.ListRequest listRequest = service.Files.List();
        listRequest.PageSize = 10;
        listRequest.Fields = "nextPageToken, files(id, name)";

        // List files.
        IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
            .Files;
        return service;
    }

    public void CreateFolderOnDrive(string Folder_Name,string ApplicationName, string credentials)
    {
        Google.Apis.Drive.v3.DriveService service = Execution(ApplicationName, credentials);

        Google.Apis.Drive.v3.Data.File FileMetaData = new
        Google.Apis.Drive.v3.Data.File();
        FileMetaData.Name = Folder_Name;
        FileMetaData.MimeType = "application/vnd.google-apps.folder";

        Google.Apis.Drive.v3.FilesResource.CreateRequest request;

        request = service.Files.Create(FileMetaData);
        request.Fields = "id";
        var file = request.Execute();
    }

    public  bool Upload(string fileName , string ApplicationName, string credentials)
    {
            DriveService service = Execution(ApplicationName, credentials);
            FilesResource.CreateMediaUpload request;
            using (var stream = new FileStream(fileName,
                                    System.IO.FileMode.Open))
            {
                var name = Path.GetFileName(stream.Name);

                var fileMetadata1 = new File()
                {

                    Name = name
                };
                request = service.Files.Create(
                    fileMetadata1, stream, "");
                request.Fields = "id";
                request.Upload();
            }
            var file = request.ResponseBody;
        return true;
    }

 }


And this is my Windows service:
 public TestService()
    {
        InitializeComponent();
        timeDelay = new System.Timers.Timer(/*1000 * 60*//*900000*/);
        timeDelay.Elapsed += new System.Timers.ElapsedEventHandler(WorkProcess);
        timeDelay.Start();
    }
    public void WorkProcess(object sender, EventArgs e)
    {
        try
        {
            //some code
            {
                //some code

                foreach (//some code)
                {
                    using (//some code)
                    {
                        // select all files to play
                        List<FILES> files = srvFile.FilesToPlay(dt_date, dt_day, dt_Hour_Minute, dt_Hour, dt_Minute, dt_Day_Name.ToString());

                        using (//some code)
                        {
                            process = "NO FILE IS RUNNING";
                            // Console.WriteLine("NO FILE IS RUNNING");
                            foreach (FILES file in files)
                            {
                                //Console.WriteLine(file.NAME + "" + "IS RUNNING NOw");
                                process = file.NAME +"IS RUNNING NOW";
                                // the function that call RepositoryGoogleDrive
                                var res = service.SentFile(file, false);

                                // call the function to create and save log
                                createLog(file);



                            }





                        }

                    } // end foreach customers

                } // end using Service_CUSTOMER
            }
        }
        catch (Exception e1)
        {
            process = e.ToString();
            LogService(process);
        }
        LogService(process);

    }


And this where i called RepositoryGoogleDrive:
if (//some code)
            {   //here folder .zid is created fine
                tmpFiles1 = TmpToZip.zip(file, tmpFiles1, tmpFolder1);
      //this code is ignored by windows service dont konw whyy !!!!!
                RepositoryGoogleDrive repositoryGoogleDrive = new RepositoryGoogleDrive();
                var result = repositoryGoogleDrive.Upload(tmpFolder1 + "\\" + file.CONFIG_FILE.NAME + ".zip", file.GOOGLE_DRIVE_CONFIG.APPLICATION_NAME, file.GOOGLE_DRIVE_CONFIG.CREDENTIALS);
                FileInfo fi1 = new FileInfo(tmpFolder1 + "\\" + file.CONFIG_FILE.NAME + ".zip");
                fi1.Delete();
                
            }}
 
Personally, the thing that I found that is the usual stumbling block for conversion of code from console code to Windows service code is permissions. More often than not, the account running as the Windows service doesn't have sufficient permissions to access the resources that the service needs.

I recommend running you Windows service, attach to the service with Visual Studio, and step through the code. I don't think it's ignoring that line of code. I think it maybe quietly failing.
 
how can i attach it with visual studio ? i have no idea how , I've tried to log the exception but nothing showed
thank you.
 
If you want to upload file to google drive without asking user for credentials you need to use service account.



Looks like you are not doing that.


To make console app as Windows services, take a look here

 
Back
Top Bottom