Skip to content

Commit 2fd1240

Browse files
[BaseTasks] Fix NRE in DeleteFile catch block (#342)
Use pattern matching (`if (log is TaskLoggingHelper helper)`) instead of an unconditional `as` cast + dereference. When `log` is null or not a TaskLoggingHelper, the original deletion exception is now silently caught instead of being masked by a NullReferenceException. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 92d4a39 commit 2fd1240

2 files changed

Lines changed: 19 additions & 2 deletions

File tree

src/Microsoft.Android.Build.BaseTasks/Files.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -613,8 +613,9 @@ public static void DeleteFile (string filename, object log)
613613
try {
614614
File.Delete (filename);
615615
} catch (Exception ex) {
616-
var helper = log as TaskLoggingHelper;
617-
helper.LogErrorFromException (ex);
616+
if (log is TaskLoggingHelper helper) {
617+
helper.LogErrorFromException (ex);
618+
}
618619
}
619620
}
620621

tests/Microsoft.Android.Build.BaseTasks-Tests/FilesTests.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -726,5 +726,21 @@ public void ToHashString ()
726726
var expected = BitConverter.ToString (bytes).Replace ("-", string.Empty);
727727
Assert.AreEqual (expected, Files.ToHexString (bytes));
728728
}
729+
730+
[Test]
731+
public void DeleteFile_NullLog_DoesNotThrow ()
732+
{
733+
var path = Path.Combine (tempDir, "directory-instead-of-file");
734+
Directory.CreateDirectory (path);
735+
Assert.DoesNotThrow (() => Files.DeleteFile (path, null));
736+
}
737+
738+
[Test]
739+
public void DeleteFile_NonTaskLoggingHelperLog_DoesNotThrow ()
740+
{
741+
var path = Path.Combine (tempDir, "directory-instead-of-file-nontasklog");
742+
Directory.CreateDirectory (path);
743+
Assert.DoesNotThrow (() => Files.DeleteFile (path, "not a TaskLoggingHelper"));
744+
}
729745
}
730746
}

0 commit comments

Comments
 (0)