该进程无法访问Log.txt文件

时间:2016-11-15 14:04:41

标签: c# .net filestream streamwriter

我有一个Windows服务,它从IoT Hub读取信息,它会记录所有内容,但是我收到此错误 该过程无法访问该文件。

我最好的猜测,因为有些东西是异步的,是另一个线程正在尝试写入日志,而其中一个正在写入它。

Service1cs

 public partial class Service1 : ServiceBase
    {
        EventProcessorHost _eventProcessorHost;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {          
            try
            {
                System.Diagnostics.Debugger.Launch(); //para hacer debugger
                WriteMessageLog($"Inicio lectura mensajes : {DateTime.Now}",DateTime.Now);
                string storageConnectionString =
                    $"DefaultEndpointsProtocol=https;AccountName={Configuracion.StorageAccountName};AccountKey={Configuracion.StorageAccountKey}";
                string _guid = Guid.NewGuid().ToString();
                string eventProcessorHostName = _guid;
                _eventProcessorHost = new EventProcessorHost(
                                                                eventProcessorHostName,
                                                                Configuracion.EventHubName,
                                                                EventHubConsumerGroup.DefaultGroupName,
                                                                Configuracion.EventHubConnectionString,
                                                                storageConnectionString);
                var options = new EventProcessorOptions
                {
                    MaxBatchSize = 100,
                    PrefetchCount = 10,
                    ReceiveTimeOut = TimeSpan.FromSeconds(20),
                    InitialOffsetProvider = (name) => DateTime.Now.AddDays(-7)
                };


                options.ExceptionReceived += OnExceptionReceived;
                _eventProcessorHost.RegisterEventProcessorAsync<SimpleEventProcessor>(options).Wait();

            }
            catch (Exception ex)
            {
                WriteMessageLog($"Error WindowsService; {ex.Message}", DateTime.Now);
                WriteMessageLog($"Error WindowsService; {ex.StackTrace}",DateTime.Now);
                //throw ex;
            }

        }



        public void WriteMessageLog(string msg, DateTime now)
        {
            try
            {
                Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
                var path = Environment.CurrentDirectory;
                string newPath = Path.GetFullPath(Path.Combine(path, @"..\..\LogTempSense.txt"));

                if (!File.Exists(newPath))
                {
                    using (StreamWriter sw = File.CreateText(newPath))
                    {
                        string logLine = $"{GetTimeStamp(now):G}   Mensaje: {msg}.";
                        sw.WriteLine(logLine);
                        sw.Close();
                    }
                }
                else
                {
                    using (StreamWriter file = new StreamWriter(newPath, true))
                    {
                        string logLine = $"{GetTimeStamp(now):G}   Mensaje: {msg}.";
                        file.WriteLine(logLine);
                        file.Close();
                    }
                }
            }
            catch (Exception e)
            {
                WriteMessageLog($"Error escribiendo log; {e.Message}",DateTime.Now);
            }
        }

        private string GetTimeStamp(DateTime now)
        {
            return string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                 "{0:D2}/{1:D2}/{2:D2} {3:D2}:{4:D2}:{5:D2}:{6:D3}",
                                 now.Day,
                                 now.Month,
                                 now.Year,
                                 now.Hour,
                                 now.Minute,
                                 now.Second,
                                 now.Millisecond);
        }

        public void OnExceptionReceived(object sender, ExceptionReceivedEventArgs args)
        {
            WriteMessageLog(String.Format("Error Event Hub exception received; {0} ", args.Exception.Message), DateTime.Now);
        }

        public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
        {
        }

        protected override void OnStop()
        {
            _eventProcessorHost.UnregisterEventProcessorAsync().Wait();
            WriteMessageLog($"Fin lectura mensajes : {DateTime.Now}", DateTime.Now);
        }
    }

SimpleEventProcesor.cs

class SimpleEventProcessor : IEventProcessor
    {
        Service1 Service1 = new Service1();
        Stopwatch _checkpointStopWatch;

        async Task IEventProcessor.CloseAsync(PartitionContext context, CloseReason reason)
        {
            Service1.WriteMessageLog(string.Format("Processor Shutting Down. Partition '{0}', Reason:'{1}'.", context.Lease.PartitionId, reason),DateTime.Now);
            if (reason == CloseReason.Shutdown)
            {
                await context.CheckpointAsync();
            }
        }

        Task IEventProcessor.OpenAsync(PartitionContext context)
        {
            Service1.WriteMessageLog(string.Format("SimpleEventProcessor initialized. Partition:'{0}',offset:'{1}'", context.Lease.PartitionId, context.Lease.Offset),DateTime.Now);
            _checkpointStopWatch = new Stopwatch();
            _checkpointStopWatch.Start();
            return Task.FromResult<object>(null);               

        }

        public Task ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
        {
            int messageCount = 0;
            foreach (EventData eventData in messages)
            {
                messageCount++;
                string data = Encoding.UTF8.GetString(eventData.GetBytes());
                JObject o = JObject.Parse(data);
                var deviceId = int.Parse(o["deviceId"].ToString()); 
                var value = decimal.Parse(o["valor"].ToString());
                var date = DateTime.Parse( o["fecha"].ToString());
                using (ActiveSenseContext db = new ActiveSenseContext(ConfigurationManager.ConnectionStrings["TempsenseConnection"].ConnectionString))
                {
                    try
                    {
                         var dispositivo = db.Dispositivos
                            .Where(p => p.DispositivoID == deviceId);

                        if (dispositivo.ToList().Count > 0)
                        {
                            Medida medida = new Medida()
                            {
                                DispositivoID = dispositivo.FirstOrDefault().DispositivoID,
                                Valor = value,
                                FechaHora = date,
                            };
                            Service1.WriteMessageLog(
                                $"Message received. Partition:{context.Lease.PartitionId}, Data:{data}{eventData.EnqueuedTimeUtc}",DateTime.Now);

                            if (bool.Parse(ConfigurationManager.AppSettings["AddDataInAppEngine"].ToString()))
                            {
                                using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["TempsenseConnection2"].ConnectionString))
                                {
                                    SqlCommand cmd = new SqlCommand();
                                    cmd.Connection = sqlConn;
                                    cmd.CommandText = "INSERT INTO TempSense_AppEngine_Medidas (Valor, FechaHora, DispositivoI) VALUES(" + medida.Valor + "," + medida.FechaHora + "," + medida.DispositivoID + ")";
                                    //cmd.CommandText = "INSERT INTO TempSense_AppEngine_Dispositivo (DispositivoI) VALUES(" + medida.DispositivoID + ")";
                                    cmd.ExecuteNonQuery();
                                }

                                db.Medidas.Add(medida);
                                db.SaveChanges();
                            }
                            else
                            {
                                db.Medidas.Add(medida);
                                db.SaveChanges();
                            }

                        }
                        else
                        {
                            Service1.WriteMessageLog(
                                $"Device Key not found in database:{o["deviceKey"]}, Message:{o}",DateTime.Now);
                        }
                    }
                    catch (Exception ex)
                    {
                        Service1.WriteMessageLog($"Mensaje tuvo error:{ex.Message},{data}",DateTime.Now);
                    }
                }
            }

            if (messageCount > Configuracion.TamanoLoteMensajes)

                context.CheckpointAsync();
                return Task.FromResult<object>(null);
        }
    }

堆栈跟踪

 en System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   en System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   en System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   en System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost)
   en System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
   en System.IO.StreamWriter..ctor(String path, Boolean append)
   en ActiveSense.Tempsense.WindowsService.Utilities.WriteMessageLog(String msg, DateTime now) en C:\Desarrollo Software\2. Sprint Execution\3. Construcción\Dev2\ActiveSense.Tempsense.web\ActiveSense.Tempsense.WindowsService\Utilities.cs:línea 32

0 个答案:

没有答案