Worker service create file on the fly in deployment not working

Dani_S 4,501 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#
{count} votes

1 answer

Sort by: Most helpful
  1. Jack J Jun 25,296 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 Answers by the question author, which helps users to know the answer solved the author's problem.