Worker service create file on the fly in deployment not working

Dani_S 5,581 Reputation points
2022-06-02T12:21:16.353+00:00

Hi,
When I create file on the fly , when debugging everting is OK.
But when I deployed and install the worker service I get error:
System.IO.FileNotFoundException: Could not find file
The code is :
if (!File.Exists(fileName))
{

                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.OmitXmlDeclaration = true;
                settings.NewLineOnAttributes = true;
                settings.ConformanceLevel = ConformanceLevel.Auto;

                using (XmlWriter writer = XmlWriter.Create(fileName, settings))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement(Constants.UsersRootElement);

                    writer.WriteStartElement(Constants.UserElement);

                    writer.WriteElementString(Constants.IsActive, true.ToString());
               ......

                    writer.WriteEndElement();

                    writer.WriteEndDocument();
                    writer.Flush();
                }
            }

Thnaks,

Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

1 answer

Sort by: Most helpful
  1. Jack J Jun 25,316 Reputation points
    2022-06-14T09:12:30.85+00:00

    @Dani_S , thanks for the feedback, based on my search, I find that it may be related your code about create the xml file when running it as a windows service. Please refer to the question FileNotFoundException when running a Windows Service to use the following code to set your relative path of the file.

    String path = System.Reflection.Assembly.GetExecutingAssembly().Location;  
    path = System.IO.Path.GetDirectoryName(path);  
    Directory.SetCurrentDirectory(path);  
    

    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.