Skip to content

Commit

Permalink
Fix file locking in attachments (#1377)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonCropp authored Dec 10, 2021
1 parent 83f2de3 commit 416e6b5
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## Unreleased

### Fixes

- Fix file locking in attachments ([#1377](https://github.com/getsentry/sentry-dotnet/pull/1377))

## 3.12.1

### Features
Expand Down
8 changes: 7 additions & 1 deletion src/Sentry/FileAttachmentContent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ public class FileAttachmentContent : IAttachmentContent
public FileAttachmentContent(string filePath) => _filePath = filePath;

/// <inheritdoc />
public Stream GetStream() => File.OpenRead(_filePath);
public Stream GetStream() => new FileStream(
_filePath,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite,
bufferSize: 4096,
useAsync: true);
}
}
42 changes: 42 additions & 0 deletions test/Sentry.Tests/AttachmentTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using Sentry.Testing;

namespace Sentry.Tests;

public class FileAttachmentContentTests
{
[Fact]
public void DoesNotLock()
{
// Arrange
using var tempDir = new TempDirectory();
var filePath = Path.Combine(tempDir.Path, "MyFile.txt");
File.WriteAllText(filePath, "Hello world!");

var attachment = new FileAttachmentContent(filePath);
// Act
using (var stream = attachment.GetStream())
{
Assert.False(IsFileLocked(filePath));
}
}

private static bool IsFileLocked(string file)
{
try
{
using FileStream stream = new(file, FileMode.Open, FileAccess.ReadWrite);
stream.Close();
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}

//file is not locked
return false;
}
}

0 comments on commit 416e6b5

Please sign in to comment.