简体   繁体   中英

c#: Windows delete a file as soon as created

I'm trying to write xml file starting from JSON data using c#. I see this strange issue: file is removed as soon as created. If I debug the code, I see that file is alive until the using closing statement, after this line, file will be deleted.

Could anyone help me?

Below there is my code:

            string path = "c:\\temp\\";
        // Write JSON to XML file
        string json = "{\"WorkOrderId\":\"WOAA_002_FQjjjjjjjj\",\"WorkOrderName\":\"OP_AAA001\",\"InternalKey\":\"WOAA_002_FQ@iKey@OP_AAA001\",\"parameterDataList\":[{\"Description\":\"Valore PR\",\"InspectionType\":\"Numeric\",\"Value\":\"\",\"LowerLimit\":null,\"NominalValue\":null,\"UpperLimit\":null,\"UoM\":\"n/a\",\"Skill\":true,\"Sequence\":\"1\",\"ParameterValueALTDatetime\":\"\"},{\"Description\":\"Valore PR\",\"InspectionType\":\"String\",\"Value\":\"test\",\"LowerLimit\":null,\"NominalValue\":null,\"UpperLimit\":null,\"UoM\":\"n/a\",\"Skill\":true,\"Sequence\":\"2\",\"ParameterValueALTDatetime\":\"\"}]}";


        XmlDocument uiXmlDoc = JsonConvert.DeserializeXmlNode(json, "root");

        // Get data for compose filename
        string woId = "WOAA_PAOLO";
        string operation = "OP_AAA001";
        string dcId = "TK-18-0000000332";

        if (!path.EndsWith("\\")) path += "\\";

        //Compose filename
        string fileName = path + woId + "@" + operation + "@" + dcId + ".xml";


        //Save the xml and then cleanup
        XmlWriterSettings settings = new XmlWriterSettings { Indent = true };


        using (StreamWriter outStream = new StreamWriter(@fileName))
        {
            XmlWriter writer = XmlWriter.Create(outStream, settings);
            uiXmlDoc.Save(writer);

        }

我解决了这个问题,问题出在使用c:/ temp目录,如果我使用它可以工作的另一个目录,我认为这可能是安全性或权限问题。

I wouldn't use the root of the c drive, windows security tends to stop users from writing there without admin credentials. Use the environmental variable %temp%, it'll put the file in the user's temp folder. Here's the link for getting the environmental variable in C#

https://docs.microsoft.com/en-us/dotnet/api/system.environment.getenvironmentvariable?view=netframework-4.7.2

The other advantage is you don't have to worry about the folder not being there and it causing an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM