Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#进程无法访问另一进程使用的文件。如何解决此问题?_C#_Http_Streamreader_Xmldocument - Fatal编程技术网

C#进程无法访问另一进程使用的文件。如何解决此问题?

C#进程无法访问另一进程使用的文件。如何解决此问题?,c#,http,streamreader,xmldocument,C#,Http,Streamreader,Xmldocument,我已经发布了完整的代码以供参考 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Diagnostics; using System.Security.Cryptography; using System.Net; using System.Xml; using System.Globalization; using

我已经发布了完整的代码以供参考

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Net;
using System.Xml;
using System.Globalization;
using System.Web;
using System.Xml.Linq;


namespace micro
{
class Program
{
    static void Main(string[] args)
    {


        // To generate the signature
        // creating an object for the class 'SamplePinpointSignatureGenerator
        Program microsoft = new Program();
        String applicationId = "****";
        Debug.WriteLine("The application Id :" + applicationId);
        String applicationKey = "*******";
        Debug.WriteLine("The application Key :" + applicationKey);

        //Debug.WriteLine("The requested URI :" + signs);
        // GenerateSignature(signs, applicationId, applicationKey);
        // To read the information from the CSVfile

        var reader = new StreamReader(File.OpenRead("C:/Users/Administrator/Documents/Book3.csv"));
        //var reader = new StreamReader(File.OpenRead("C:/Users/Administrator/Documents/Book2.csv"));
        var listA = new List<String>();
        var listB = new List<String>();
        var listC = new List<String>();
        var listD = new List<String>();
        var listE = new List<String>();
        var listF = new List<String>();


        int linenumber = 0;

        while (!reader.EndOfStream)
        {
            string line = reader.ReadLine();
            if (!String.IsNullOrWhiteSpace(line))
            {
                linenumber++;


                String[] values = line.Split(',');
                if (linenumber > 1)
                {

                    if (values.Length > 1)
                    {
                        listA.Add(values[0]);
                        listB.Add(values[1]);
                        listC.Add(values[2]);
                        listD.Add(values[3]);
                        listE.Add(values[4]);
                        listF.Add(values[5]);

                    }
                }

            }
        }
        String path = "C:/Users/Administrator/Downloads/pinpoint1.csv";
        var w = new StreamWriter(path);
        var line1 = string.Format("AdvertiserName" + "," + "BusinessNeedNumber" + "," + "IndustryFocusNumber" + "," + "Competency" + "," + "URL" + "," + "Signauture" + "," + "SignatureURL");// + "," + "State" + "," + "City" + "," + "Country" + "," + "UniqueId" + "," + "ProfileURL");
        w.WriteLine(line1);
        w.Flush();

        String[] firstlistA = listA.ToArray();
        String[] firstlistB = listB.ToArray();
        String[] firstlistC = listC.ToArray();
        String[] firstlistD = listD.ToArray();
        String[] firstlistE = listE.ToArray();
        String[] firstlistF = listF.ToArray();
        for (int i = 0; i < firstlistD.Length; i++)
        {
            String a = firstlistA[i].Replace("\"", "");
            String b = firstlistB[i].Replace("\"", "");
            String c = firstlistC[i].Replace("\"", "");
            String d = firstlistD[i].Replace("\"", "");
            String e = firstlistE[i].Replace("\"", "");
            String fy = firstlistF[i].Replace("\"", "");

            String URLdata = d + "," + e + "," + fy;
            Debug.WriteLine(URLdata);
            Uri signs = new Uri(URLdata);
            //Debug.WriteLine("The requested URI :" + signs);
            String signature = GenerateSignature(signs, applicationId, applicationKey);
            String sig = signature.Replace("=", "%3d");
            String g = sig.Replace("/", "%2f");
            String f = g.Replace("+", "%2b");
            String q1 = String.Concat("\"", URLdata, "&sig=", f, "\"");
            String q = String.Concat(URLdata, "&sig=", f);
            Debug.WriteLine("BusinessNeedNumber :" + a + " IndustryFocusNumber :" + b + " Competency :" + c + " The URL :" + d + " : The signature URL :" + q);

            var data = string.Format(a + "," + b + "," + c + "," + signature + "," + q1);

            w.WriteLine(data);
            w.Flush();
            // Generate the XML file for information parsing
            String ab = microsoft.GenerateXML(q);
            // XmlDocument content2 = new XmlDocument();

            // content2.LoadXml(ab);

            //  content2.Save("C:/Users/Administrator/Downloads/direct.xml");

            ReadXMLfile(ab);

        }
    }
    public String GenerateXML(String q)
    {
        // Generating the XML file for reference
        // Getting the response in XML format from the URL

        Debug.WriteLine("The Http URL after URL encoding :" + q);
        Uri signs1 = new Uri(q);
        //Debug.WriteLine("The Requested URL for getting the XML data :" + re);

        WebRequest request1 = WebRequest.Create(signs1);


        HttpWebResponse response1 = (HttpWebResponse)request1.GetResponse();

        Stream receiveStream = response1.GetResponseStream();

        StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

        String ab = readStream.ReadToEnd();
        // Debug.WriteLine("The data :"+a);
        //XmlDocument content2 = new XmlDocument();

        // content2.LoadXml(ab);

        //  content2.Save("C:/Users/Administrator/Downloads/direct.xml");
        return ab;
    }

    public static string GenerateSignature(Uri pinpointSyndicationRequest, string applicationId, string applicationKey)
    {
        if (null == pinpointSyndicationRequest)
        {
            throw new ArgumentNullException("pinpointSyndicationRequest");
        }
        if (String.IsNullOrEmpty(applicationId))
        {
            throw new ArgumentNullException("applicationId");
        }
        if (String.IsNullOrEmpty(applicationKey))
        {
            throw new ArgumentNullException("applicationKey");
        }

        //
        // Extract the path and query from the supplied URI
        // The hash should ONLY include the page and query (scheme, host, and port are omitted).
        //
        // e.g.,
        // http://pinpoint.microsoft.com/en-US/syndicate/Partners/?view=v2010.05
        //                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        //
        string request = pinpointSyndicationRequest.PathAndQuery;
        //Debug.WriteLine("The path and the query of the requested URI :" + request);

        //
        // Hash the path and query
        //
        string requestHash = GenerateHashBase64(applicationKey, request);

        //
        // Build the signature
        //
        string signature = String.Format(CultureInfo.InvariantCulture, "S-{0}-{1}", applicationId, requestHash);
        //Debug.WriteLine("The signature :" + signature);
        //
        // The signature may now be appended to the URI (in the "sig=..." query param)
        // or included as an HTTP header (as "Syndication-Sig: ...").
        //
        // If the request is appended to the URI, it must be escaped first to encode
        // Base64 characters which cannot be included verbatim in the URI.
        //


        return signature;
    }

    /// <summary>
    /// Generate a Base64-encoded SHA256 HMAC of the supplied string
    /// </summary>
    /// <param name="key">Key supplied to HMAC</param>
    /// <param name="content">String to hash</param>
    /// <returns>Base64-encoded HMAC of key and content</returns>
    private static string GenerateHashBase64(string key, string content)
    {
        if (String.IsNullOrEmpty(key))
        {
            throw new ArgumentNullException("key");
        }
        if (String.IsNullOrEmpty(content))
        {
            throw new ArgumentNullException("content");
        }

        // Convert inputs to byte arrays
        byte[] keyBytes = Encoding.Unicode.GetBytes(key);
        byte[] contentBytes = Encoding.Unicode.GetBytes(content);

        // Compute the cryptographic hash
        HMACSHA256 hmac = new HMACSHA256(keyBytes);
        byte[] hash = hmac.ComputeHash(contentBytes);

        // Convert to base64
        string result = Convert.ToBase64String(hash);
        //Debug.WriteLine("the base64 hash :" + result);

        return result;
    }

    // Method to read the XML
    public static void ReadXMLfile(String ab)
    {
        //System.Threading.Thread.Sleep(10000);
        XmlDocument content2 = new XmlDocument();

            content2.LoadXml(ab);

            content2.Save("C:/Users/Administrator/Downloads/direct.xml");// The process cannot access the file 'C:\Users\Administrator\Downloads\direct.xml' because it is being used by another process.

            String path1 = "C:/Users/Administrator/Downloads/pinpoint2.csv";

         using(var w1 = new StreamWriter(path1))
        {
        // Read and parse the required information from 'direct.xml'

            var reader1 = new StreamReader("C:/Users/Administrator/Downloads/direct.xml");

            var xmlDoc1 = XDocument.Load(reader1);

            XNamespace atom = "http://www.w3.org/2005/Atom";
            XNamespace metadata = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
            XNamespace dataservices = "http://schemas.microsoft.com/ado/2007/08/dataservices";

            var result = xmlDoc1.Root.Elements(atom + "entry")
.Select(e => new
{
    Title = (string)e.Element(atom + "title"),
    Id = (string)e.Element(atom + "id"),
    Urls = e.Elements(atom + "link")
        .Where(l => l.Element(metadata + "inline") != null)
        .SelectMany(l => l.Element(metadata + "inline")
            .Element(atom + "feed")
            .Elements(atom + "entry")
            .Select(e1 => (string)e1.Element(atom + "content")
                .Element(metadata + "properties")
                .Element(dataservices + "Url")).Where(k => k != null)),
    City = e.Elements(atom + "link")
       .Where(l => l.Element(metadata + "inline") != null)
       .SelectMany(l => l.Element(metadata + "inline")
           .Element(atom + "feed")
           .Elements(atom + "entry")
           .Select(e1 => (string)e1.Element(atom + "content")
               .Element(metadata + "properties")
               .Element(dataservices + "City")).Where(u => u != null)),
    State = e.Elements(atom + "link")
       .Where(l => l.Element(metadata + "inline") != null)
       .SelectMany(l => l.Element(metadata + "inline")
           .Element(atom + "feed")
           .Elements(atom + "entry")
           .Select(e1 => (string)e1.Element(atom + "content")
               .Element(metadata + "properties")
               .Element(dataservices + "State")).Where(u => u != null)),
    Country = e.Elements(atom + "link")
       .Where(l => l.Element(metadata + "inline") != null)
       .SelectMany(l => l.Element(metadata + "inline")
           .Element(atom + "feed")
           .Elements(atom + "entry")
           .Select(e1 => (string)e1.Element(atom + "content")
               .Element(metadata + "properties")
               .Element(dataservices + "Country")).Where(u => u != null))
});

            foreach (var entry in result)
            {
                foreach (var sta in entry.State)
                {

                    foreach (var ci in entry.City)
                    {
                        foreach (var coun in entry.Country)
                        {
                            foreach (var url in entry.Urls)
                            {
                                Debug.WriteLine("{0},{1},{2},{3}", entry.Title, entry.Id, ci, url);

                                String uniqueId = sta + ci + coun;
                                Debug.WriteLine(uniqueId);
                                // Writing onto CSV file
                                String advertisername = entry.Title.Replace(",", "&");
                                var data = string.Format(advertisername + "," + sta + "," + ci + "," + coun + "," + uniqueId + "," + url);

                                w1.WriteLine(data);
                                w1.Flush();

                            }
                        }
                    }


                }
            } w1.Close();
            return;
        }
    }
}

我不知道如何解决这个问题,c#编程新手,请在这个过程中帮助我。感谢您的帮助。提前感谢。

从帖子上看,您似乎无权访问该位置。或者,如果已经存在同名文件,则该文件正被另一个进程使用。您无法替换或删除正在使用的文件。

至少在这个问题上,我在w1.close()之后使用了return1.close()。

您确定了哪个进程打开了文件吗?怎么做?正如c#新提到的那样,@Sean:能够解决这个问题,必须执行w.Close()和w1.Close(),并在as->var w1=new StreamWriter(path1)和return1.Close()中包含“true”;如何避免这种情况,你知道吗?你可以找出哪个服务正在使用这个文件。我返回了1.close(),它确实起了作用。现在我想附加到文件,而不是覆盖。怎么做有什么想法吗?附加模式是这样吗?您至少知道这里如何做吗?FileStream readStream=newfilestream(path,FileMode.Append);这可能对你有帮助
content2.Save("C:/Users/Administrator/Downloads/direct.xml");// The process cannot access the file 'C:\Users\Administrator\Downloads\direct.xml' because it is being used by another process.